如何在 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:
- 在子类构造函数中,
this
不能使用,直到super
被调用. - 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屋!