具有相同名称的Field,getter和setter

时间:2016-02-13 13:51:01

标签: javascript

你能解释我为什么

  

未捕获RangeError:超出最大调用堆栈大小

在这个例子中

。什么是行动的顺序?

"use strict";

let myClass = class myClass{
  constructor(name){ 
    this.name = name;
  } 
  get name() { return this.name; } 
  set name(name){ this.name = name; }
}  

let myObj = new myClass("John");

1 个答案:

答案 0 :(得分:7)

你从setter中调用setter,无限循环。

set name(name) {
  this.name = name; // <-- `this.name` calls the `set`ter again
}

您应该使用某种不同名称的支持变量:

&#13;
&#13;
"use strict";

let myClass = class myClass {
  constructor(name) {
    this.name = name;
  }

  get name() {
    return this._name;
  }

  set name(name) {
    this._name = name;
  }
}

let myObj = new myClass("John");

console.log(myObj);
&#13;
&#13;
&#13;

令我惊讶it's not trivial to have variables private to a class