简体   繁体   中英

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

I couldn't figure out this, but maybe anyone can help me: When I define a javascript class and try to add a static attribute "name", I can't use "name" afterwards.

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);

I would expect it to output all 4 strings. But instead it will only output:

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

This works fine!

It doesn't accept the static attribute "name", but why? Any ideas/hints? Thanks in advance!

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

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