Javascript ES6 JS类下划线set和get方法返回;超过最大调用堆栈大小;
我试图理解JSES6类,当我引用“this.”变量时,我的问题是“超过了最大调用堆栈大小”。让我们看看这个例子:Javascript ES6 JS类下划线set和get方法返回;超过最大调用堆栈大小;,javascript,class,ecmascript-6,underscore.js,Javascript,Class,Ecmascript 6,Underscore.js,我试图理解JSES6类,当我引用“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:
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文档中甚至没有下划线。使用
设置年龄的关键在于定义一个名为age
的setter
如果setter的实现只执行this.age=
,那么您就是递归地调用setter
不能同时使用名为age
的setter和名为age
的成员变量。它们必须被称为不同的东西,例如age
和\u age
使用设置年龄
的全部目的是定义一个名为age
的设置器
如果setter的实现只执行this.age=
,那么您就是递归地调用setter
不能同时使用名为age
的setter和名为age
的成员变量。它们必须被称为不同的事物,例如age
和\u age
这对于注释来说太长了。要补充Meagar(正确)的答案:
这上面有糖吗
instance.foo = val;
因此,每当其他代码设置foo
属性时,就会调用setter。设置程序存在的原因是为了防止您需要执行其他操作,例如运行一些验证以查看值是否有效。因此,当您拥有setter时,它会被调用
instance.foo = val;
那么在二传中你有
set foo (val) {
this.foo = val;
}
它实际上是在调用自己。这对于注释来说太长了。要补充Meagar(正确)的答案:
这上面有糖吗
instance.foo = val;
因此,每当其他代码设置foo
属性时,就会调用setter。设置程序存在的原因是为了防止您需要执行其他操作,例如运行一些验证以查看值是否有效。因此,当您拥有setter时,它会被调用
instance.foo = val;
那么在二传中你有
set foo (val) {
this.foo = val;
}
它实际上是在调用自己