JS类中的字段挂载到了哪里
class Person {
name = 'cinnamon'
age = 20
constructor() { this.gender = 0 }
getInfo() {
return {
name: this.name,
age: this.age,
gender: this.gender
}
}
}
class Person {
name = 'cinnamon'
age = 20
constructor() { this.gender = 0 }
getInfo() {
return {
name: this.name,
age: this.age,
gender: this.gender
}
}
}
Person.prototype
获取name
, age
, gender
字段时,输出为undefined
,而且当我通过控制台输出Person.prototype
时,里面只有constructor
和我定义的getInfo
。当我new Person()
得到实例时,字段却出现在了实例里。所以问题就在于类中的字段到底放在了哪里,如果不是prototype
那其实例是怎么获取字段的。
class Person {
constructor(name,age) {
this.gender = 0;
this.name = name;
this.age = age;
}
getInfo() {
return {
name: this.name,
age: this.age,
gender: this.gender
}
}
}
参考一下,如果帮助到你,请采纳