为什么我不能使用“name”呢?javascript / nodeJS中的静态属性

Why can't I use "name" as static attribute in javascript / nodeJS

本文关键字:nodeJS javascript 属性 静态 不能 name 为什么      更新时间:2023-09-26

我不明白这个,但也许有人可以帮助我:当我定义一个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",但为什么呢?有什么想法/提示吗?提前感谢!

函数对象的name属性为read-only,对它的赋值将被忽略。