我在使用Gulp运行babelify 7.2.0时遇到以下代码错误:
class One {}
class Two extends One {
constructor() {
this.name = 'John';
}
}
以下是错误的关键:
SyntaxError: [the file path in question]: 'this' is not allowed before super()
20 | class Two extends One {
21 | constructor() {
> 22 | this.name = 'John';
| ^
23 | }
24 | }
25 |
在我看来,这不应该被触发,因为我根本没有在构造函数中进行任何super
调用,因此没有冲突的风险。我已经在Github上提交了一个问题,但我想知道是否有办法在同一时间关闭它。
答案 0 :(得分:6)
这不是错误。在尝试访问super
之前,子类必须明确地调用this
:
class Two extends One {
constructor(...args) {
super(...args);
this.name = 'John';
}
}
这是在ECMAScript标准中定义的(见this回答),而Babel则密切关注它。
答案 1 :(得分:0)
不,没有办法“关闭它”,因为这是ECMAScript 2015标准中定义的要求。
在this
调用扩展类的构造函数之前, super(...)
不可用。
可以在this answer中看到标准中定义的详细位置的详细信息。
答案 2 :(得分:0)
这不是Babel的事情,它是在ES2015中定义的。你不能把它关掉。
在派生构造函数中,this
在调用super
之前未定义。与(比如)Java不同,对super
的调用从不隐含,您必须明确地编写它们。
主要在§9.2.2,[[Construct]] ( argumentsList, newTarget)
和§12.3.5.1中定义,super
的运行时语义:[[Construct]]
仅调用OrdinaryCallBindThis
[[ConstructorKind]]
是" base" (不是"派生")。否则,this
仍然未定义,直到您调用super
,其中一部分在超级构造函数上调用[[Construct]]
,该构造函数调用自己的super
(如果它也是派生构造函数) )或OrdinaryCallBindThis
(如果它是基础构造函数)。