2

我无法弄清楚这一点,但也许任何人都可以帮助我:当我定义一个 javascript 类并尝试添加一个静态属性“name”时,之后我不能使用“name”。

var MyClass = function() {
  this.name = 'This is an instance of MyClass';
  this.anyName = 'This has nothing to do with it';
}

// static attributes
MyClass.name = 'Why is this not possible?';
MyClass.anyName = 'This works fine!';

var a = new MyClass();
console.log(a.name);
console.log(a.anyName);
console.log(MyClass.name);
console.log(MyClass.anyName);

我希望它输出所有 4 个字符串。但它只会输出:

This is an instance of MyClass
This has nothing to do with it

This works fine!

它不接受静态属性“name”,但为什么呢?任何想法/提示?提前致谢!

4

1 回答 1

4

函数对象的 name 属性是只读的,对其的赋值将被忽略。

于 2013-03-03T12:53:18.587 回答