如何扩展一个类而不必在ES6中使用super? [英] How to extend a class without having to using super in ES6?
问题描述
是否可以在不调用 super
方法来调用父类的情况下扩展ES6中的类?
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()
在派生类上我遇到了范围问题 - > 这未定义
When I'm not calling super()
on the derived class I'm getting a scope problem -> this is not defined
我正在运行这与iojs - 和谐在v2.3.0
I'm running this with iojs --harmony in v2.3.0
推荐答案
ES2015(ES6)课程的规则基本上归结为:
The rules for ES2015 (ES6) classes basically come down to:
- 在子类构造函数中,
此
在之前无法使用调用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 定义了决定这个在函数中的逻辑。类的重要部分是这个
可能在未初始化的
状态,并且在此时状态,尝试使用此
将抛出异常。
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
调用的函数的行为。在调用基类构造函数时,此
在 [[Construct]]
的第8步初始化,但对于所有人其他情况,此
未初始化。在构造结束时,调用 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屋!