This._ bottom line rule of javascript class getter setter

read the MDN documentation and found no corresponding instructions, but when I actually tested it, I found that _ under the getter, setter of class is not just a naming convention, but there are really special rules. For example:

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**

getter named a can get the value of this.a through this._a . If getter is changed to return this.a; , it will loop infinitely. So it is necessary to use return this._a; , but there is no description in the document that class getter must use _.

getter named b cannot get this._a

excuse me, where can I write such a rule? Why is there such a design?

Jan.12,2022

think too much, there is no such thing.
the first example simply calls set an in the constructor


this.an originally takes getter (if it exists), so you can't use this.a, in get or it will end up in an endless loop

this is true for all languages as long as get set exists. The known oc,php needs to change the variable to private

.
Menu