我试图理解 JS ES6 类,当我引用“this”时,我的问题是“超出最大调用堆栈大小”。变量。让我们看一下这个例子:
class Human {
constructor(age) {
this.age = age;
// "this._age = age;" output:
// Property age of instance without underscore: 34
// Property age of instance with underscore: 34
}
get age() {
return this._age;
// Without underscore error: "Uncaught RangeError: Maximum call stack size exceeded"
}
set age(age) {
this._age = age;
// Without underscore error: "Uncaught RangeError: Maximum call stack size exceeded"
console.log(`Without underscore: ${this.age}`);
console.log(`With underscore: ${this._age}`);
}
}
let john = new Human(34);
console.log(`Property age of instance without underscore: ${john.age}`);
console.log(`Property age of instance with underscore: ${john._age}`);
为什么我需要在 get 和 set 方法中使用下划线?当我在构造函数中使用它时,为什么输出会发生这样的变化?为什么在引用实例属性时没有使用下划线或不使用下划线?在 mdn 文档中甚至根本没有下划线。
最佳答案
使用set age
的全部意义是您正在定义一个名为 age
的二传手.
如果你的 setter 的实现只是做 this.age = <new value>
,那么您将递归地调用 setter 。
你们不能同时拥有一个名为 age
的二传手并尝试设置一个名为 age
的成员变量.它们必须被称为不同的东西,例如 age
和 _age
.
关于javascript - ES6 JS 类下划线设置和获取方法返回 "Maximum call stack size exceeded",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46447164/