这是我的代码:
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/