【发布时间】:2016-07-16 08:23:42
【问题描述】:
既然 JavaScript 有类,我想知道如何在类构造函数之外调用超级构造函数。
我不成功的幼稚尝试(导致 SyntaxError):
class A
{
constructor() { this.a = 1; }
}
function initB()
{
super(); // How to invoke new A() on this here?
this.b = 2;
}
class B extends A
{
constructor() { initB.call(this); }
}
我知道在 Java 等其他语言中,超级构造函数只能在派生类的构造函数中调用,但 ES6 类是基于原型的继承的语法糖,所以如果这是我会感到惊讶的使用内置语言功能不可行。我似乎无法弄清楚正确的语法。
到目前为止,我最好的感觉就像作弊一样:
class A
{
constructor() { this.a = 1; }
}
function initB()
{
let newThis = new A();
newThis.b = 2;
return newThis;
}
class B extends A
{
constructor() { return initB(); }
}
【问题讨论】:
-
是什么阻止您使用标准的
class B extends A { constructor() { super(); this.b = 2; }},因为它应该是? -
您的“解决方案”实际上是语法错误。
-
@Bergi 我知道我的第一种方法是语法错误,这就是我问的原因。我澄清了我的问题,谢谢。
-
其实我的意思是第二个。是的,你的第一个 sn-p 也是一个语法错误。
-
构造函数不包含
super()调用。例如,Babel 就做到了这一点。
标签: javascript class inheritance constructor ecmascript-6