因为我还没有将 this._name
声明为属性,所以这不应该引发错误吗?为什么会自动创建?
p.s.***如果 this.name 和 this._name 是不同的属性,它不应该打印 Tom/Tom/Tom 因为 this.name 在声明后没有被更改吗?
class Person{
constructor(name){
this.name=name;
}
get name(){
return this._name;
}
set name(value){
this._name=value;
}
sayName(){
console.log(this.name);
}
}
var person=new Person("Tom");//TOM
console.log(person.name);
person.name="Huck";
console.log(person.name);//Huck
person.sayName();//Huck
最佳答案
因为在您的构造函数中您设置了 this.name
,但是 name
的 setter 实际上设置了 _name
。所以不,它不是自动创建的——JavaScript 对象在该属性尚不存在时创建该属性是正常行为。即使它已经存在,逻辑也是一样的——想想看。如果你有一个 if
语句来检查它是否存在,它会是什么样子?这:
if (this._name) this._name = value;
else this._name = value;
实际上,发生的任何事情都没有区别,因为访问未定义的属性会返回 undefined
而不是抛出错误 - 如果有帮助,您可以认为它存在,但只是 undefined
。
关于javascript - 为什么会自动创建以 '_' 开头的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57426307/