简体   繁体   中英

TypeError when class has static member `name`

I have the following TypeScript class

module Test {
    "use strict";

    class Foo {
        public static name = "foo";
    }
}

Pretty simple.

But when run in Chrome I get the following error:

Uncaught TypeError: Cannot assign to read only property 'name' of function 'function Foo() { }'

Here's the generated javascript:

 var Test; (function (Test) { "use strict"; var Foo = (function () { function Foo() { } Foo.name = "foo"; return Foo; }()); })(Test || (Test = {})); 

If I use a different name then name I don't get an error.

module Test {
    "use strict";

    class Foo {
        public static huh = "foo";
    }
}

What is going on?

The problem seems to be that you are trying to write to Function.name . In the code that you wrote initially, you can see in the compiled code that you are changing Foo.name .

Consider just this code

  function Foo(){}
  console.log(Foo.name); // prints 'Foo'

The error is because you are trying to change this function's property, and are not allowed to do so ( read-only property .. ). More information about why (and how) you are not allowed to do so can be found here . Thanks to @ssube for providing this link in the comments

So whilst you have not created that property yourself, all your functions do actually have it. You can check this page for some more information.

the problem is Foo.name = "foo"; because name is a predefined property of functions in javascript (like arguments , length and such), which holds the name of the function ('Foo' in your case) so you can't overwrite it with your own definition

have a look on Mozilla's MDN for details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM