2013-03-03 90 views
2

我无法弄清楚这一点,但也许任何人都可以帮助我: 当我定义一个JavaScript类并尝试添加一个静态属性“name “,之后我不能使用”名称“。为什么我不能在javascript/nodeJS中使用“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! 

它不接受静态属性“名称”,但为什么?任何想法/提示? 在此先感谢!

+0

[将新属性添加到函数对象](http://stackoverflow.com/questions/13352643/adding-new-properties-to-a-function-object),请参阅https:// developer。 mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/name – Bergi 2013-03-03 13:01:53

回答

4

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

+0

我得说,这很蹩脚。即使你“严格使用”;它仍然默默地失败。 – 2013-07-23 06:23:29

相关问题