使用babel 将ES6 转编译成ES5 时出现奇怪的问题。
我遇到的问题似乎与 Babel/RequireJS + typeof "RangeError: Maximum call stack size exceeded" 无关
如果您使用 default settings on babeljs.io 运行这个简单的代码片段
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
set name(name) {
this.name = name;
}
set age(age) {
this.age = age;
}
get name() {
return this.name;
}
get age() {
return this.age;
}
}
let person = new Person('John Doe', 25);
console.log(person.name);
您收到超出最大调用堆栈大小 的错误。我不确定这是为什么。根据this github issue问题解决了吗?
我已经能够在 ES5 代码中深入到这一行:
set: function set(name) { ... }
但我不确定为什么会出现错误。谁能澄清这里发生了什么或解决方法是什么?
注意:我已经在 jsfiddle、codepen、jsbin 和 js.do 上重复了这个问题。每次我尝试设置一个 调试器;
控制台都会崩溃,所以我无法检查调用堆栈。
最佳答案
该错误实际上与 Babel 无关,常规 ES6 也会爆栈,这意味着 Babel 正在产生正确的行为。
// regular ES6, no babel
class Person {
constructor(name, age) {
this.name = name;
}
set name(name) {
this.name = name;
}
get name() {
return this.name;
}
}
let person = new Person('John Doe');
您的 getters/setters 不能与它们正在操作的属性同名,因为它们最终会无限地调用自己。
get name() {
return this.name; // call the getter again which calls it again which calls it again ...
}
set name(name) {
this.name = name; // call the setter again which calls it again which calls it again ...
}
如果您只是更改属性名称(例如 _name
而不是 name
),一切正常:
class Person {
constructor(name, age) {
this._name = name;
}
set name(name) {
this._name = name;
}
get name() {
return this._name;
}
}
let person = new Person('John Doe');
console.log(person.name); // 'John Doe'
关于javascript - Babel 代码抛出超出最大调用堆栈大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40123683/