为什么我不能在javascript / nodeJS中使用“name”作为静态属性

时间:2013-03-03 12:39:39

标签: javascript node.js naming static-variables

我无法弄清楚这一点,但也许任何人都可以帮助我: 当我定义一个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”,但为什么呢?有什么想法/提示吗? 提前谢谢!

1 个答案:

答案 0 :(得分:4)

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