如何在ES6中不必使用super来扩展类? [英] How to extend a class without having to use super in ES6?
问题描述
是否可以在ES6中扩展类而无需调用super
方法来调用父类?
Is it possible to extend a class in ES6 without calling the super
method to invoke the parent class?
该问题可能会引起误解.是我们必须称呼super()
的标准,还是我遗漏了一些东西?
The question might be misleading. Is it the standard that we have to call super()
or am I missing something?
例如:
class Character {
constructor(){
console.log('invoke character');
}
}
class Hero extends Character{
constructor(){
super(); // exception thrown here when not called
console.log('invoke hero');
}
}
var hero = new Hero();
当我没有在派生类上调用super()
时,我遇到了范围问题-> this is not defined
When I'm not calling super()
on the derived class I'm getting a scope problem -> this is not defined
我正在v2.3.0中使用iojs --harmony运行
I'm running this with iojs --harmony in v2.3.0
推荐答案
ES2015(ES6)类的规则基本上归结为:
The rules for ES2015 (ES6) classes basically come down to:
- 在子类构造函数中,只有在调用
super
之前,才能使用this
. - ES6类构造函数如果是子类,则必须调用
super
,否则它们必须显式返回某个对象以代替未初始化的对象.
- In a child class constructor,
this
cannot be used untilsuper
is called. - ES6 class constructors MUST call
super
if they are subclasses, or they must explicitly return some object to take the place of the one that was not initialized.
这归结为ES2015规范的两个重要部分.
This comes down to two important sections of the ES2015 spec.
8.1.1.3.4 部分定义了逻辑决定函数中的this
.类的重要部分是this
可能处于"uninitialized"
状态,并且在此状态下尝试使用this
会引发异常.
Section 8.1.1.3.4 defines the logic to decide what this
is in the function. The important part for classes is that it is possible for this
be in an "uninitialized"
state, and when in this state, attempting to use this
will throw an exception.
第 9.2.2 ,[[Construct]]
,它定义了通过new
或super
调用的函数的行为.调用基类构造函数时,this
在[[Construct]]
的步骤#8处初始化,但是对于所有其他情况,this
未初始化.在构造结束时,将调用GetThisBinding
,因此,如果尚未调用super
(因此初始化this
),或者未返回显式替换对象,则构造函数调用的最后一行将引发异常.
Section 9.2.2, [[Construct]]
, which defines the behavior of functions called via new
or super
. When calling a base class constructor, this
is initialized at step #8 of [[Construct]]
, but for all other cases, this
is uninitialized. At the end of construction, GetThisBinding
is called, so if super
has not been called yet (thus initializing this
), or an explicit replacement object was not returned, the final line of the constructor call will throw an exception.
这篇关于如何在ES6中不必使用super来扩展类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!