简单 ES6 属性 调用超出最大调用堆栈大小

Maximum call stack size exceeded on simple ES6 property call

这是我的代码:

class Drone {
  constructor(id, name) {
    this._id = id;

  }
  static getCompany() {
    console.log('in getCompany');
  }
  fly() {
    console.log('Drone ' + this.id + ' is flying.')
  }

  get id() {
    console.log('in id getter');
    return this.id + 'TEMPORARY';
  }

}

let drone = new Drone('A12');
console.log('drone id: ' + drone.id);

当我 运行 来自 index.html 时,我得到一个 'maximum call stack size exceeded'。但是代码中根本没有迭代。

I'm getting a 'maximum call stack size exceeded'. But there is no iteration at all in the code.

实际上您的代码中有迭代,只是有点难以发现,因为您使用的是 getter。由于方法 id() 是一个 getter,您可以在不使用括号 () 的情况下执行它。这意味着当您执行 this.id 时,您实际上是在调用您的 getter。目前您在 getter 中使用 this.id,导致无限递归,从而导致堆栈溢出。相反,您需要使用 this._id 来引用实例的 _id 属性,而不是 getter 方法:

class Drone {
  constructor(id, name) {
    this._id = id;

  }
  static getCompany() {
    console.log('in getCompany');
  }
  fly() {
    console.log('Drone ' + this.id + ' is flying.')
  }

  get id() {
    console.log('in id getter');
    return this._id + 'TEMPORARY'; // Change `this.id` to `this._id` 
  }

}

let drone = new Drone('A12');
console.log('drone id: ' + drone.id);

在你的 getter 中,你需要将 return this.id + 'TEMPORARY'; 更改为 return this._id + 'TEMPORARY';..

你一遍又一遍地递归调用 getter。

class Drone {
  constructor(id, name) {
    this._id = id;

  }
  static getCompany() {
    console.log('in getCompany');
  }
  fly() {
    console.log('Drone ' + this.id() + ' is flying.')
  }

  get id() {
    console.log('in id getter');
    return this._id + 'TEMPORARY';
  }

}

let drone = new Drone('A12');
console.log('drone id: ' + drone.id);

编辑:

由于 OP 询问为什么会发生这种情况(递归),因此我创建了这个示例:

// Recursion demo
function CountDownFrom(number) {
  if(number > 0) {
    console.log(number);
    // This line here is what causes recursion.
    // Essentially, this function calls itself over and over.
    CountDownFrom(number - 1);
    // ^^ this line causes recursion
  }
  if(number === 0) {
    console.log("END");
  }
}

CountDownFrom(10);