【问题标题】:Field, getter and setter with the same name同名的字段、getter 和 setter
【发布时间】:2016-02-13 13:51:00
【问题描述】:

你能解释一下为什么我得到了

未捕获的 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");

【问题讨论】:

    标签: javascript


    【解决方案1】:

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

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

    您应该使用某种不同命名的支持变量。不幸的是,JS 的“TC39 Private Fields”提案尚未最终确定,因此它们将是公开的,目前需要一个命名约定。

    这是一个现代示例:

    class Person {
      _name = ""; // 'private' by convention, see also: https://github.com/tc39/proposal-class-fields#private-fields
      get name() {
        return this._name;
      }
      set name(value) {
        this._name = value;
      }
    
      constructor(name) {
        this.name = name;
      }
    }
    

    或遵循问题的结构:

    "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);

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

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-29
    • 2011-12-29
    • 2011-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多