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

标签 javascript es6-class

这是我的代码:

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 运行此命令时,我收到“超出最大调用堆栈大小”的消息。但代码中根本没有迭代。

最佳答案

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

关于javascript - 简单 ES6 属性调用超出了最大调用堆栈大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59297328/

相关文章:

javascript - 我如何引用一个以字符串形式命名的类?

javascript - 使用javascript平滑自动滚动

javascript - 我可以在哪里调度 Action - redux?

javascript - Jquery 验证插件名称与 Zend_Form 冲突

Javascript - 将类实例保存到哈希表/对象中并使用键实例函数

javascript - 类装饰器(实例级)

javascript - 导入实例化类设置全局原型(prototype)

angular - 编译为 ES5 时在 TypeScript (Angular 2+) 中扩展 EventTarget

javascript - 未捕获的类型错误 : callback is not a function while implementing pusher with laravel

javascript - 阻止 AngularJS 不执行 HTML 标签