看了MDN的文档 没有找到相对应的说明,但自己实际测试时,发现 _ 在 class 的 getter, setter 下,并不只是一个命名惯例,而是真的有特殊规则。例如:
class Test{
constructor(){
this.a = 1;
}
get a(){
return this._a;
}
set a(value){
this._a = value;
}
}
const t = new Test();
**console.log('t.a', t.a); //1**
class Test2{
constructor(){
this.a = 1;
}
get b(){
return this._a;
}
set b(value){
this._a = value;
}
}
const t2 = new Test2();
**console.log('t2.b', t2.b); //undefined**
名为 a 的 getter 可以透过 this._a
取得 this.a
的值,若 getter
改为 return this.a;
则会无限迴圈。所以使用 return this._a;
是必要的,但在文档中并没有 class getter 必须要用 _ 的说明。
名为 b 的 getter 就无法得到 this._a
请问这样的规则在哪裡有写呢?为什麽会有这样的设计呢?
想多了,没有的事。
第一个例子只是在构造方法里面调用了set a而已