javascript - ES6 JS 类下划线设置和获取方法返回 "Maximum call stack size exceeded"

标签 javascript class ecmascript-6 underscore.js

我试图理解 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/

相关文章:

javascript - ref 未引用数组中的正确项目

c++ - 如何 "inherit"来自 STL 类的迭代器?

Java 扩展 vs 对象引用?

javascript - 将具有唯一 id 属性的对象数组转换为 Map

javascript - Redux 状态更改后 React 容器不会重新渲染

javascript - 在 react 中将 ref 传递给父级

php - 如何自动化数据收集而不卡住 10%

javascript - 如何对使用的特定 jQuery(和 Javascript)方法/函数进行特征检测/测试

c++ - 大小未知的数组作为类成员,用于在运行时制作数组对象(对象创建时间)

javascript - 如何在使用 fetch 时动态循环 for 循环中的多个 Promise?