相关疑难解决方法(0)

如何在构造函数外调用超级构造函数?

既然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); }
}
Run Code Online (Sandbox Code Playgroud)

我知道在像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(); }
}
Run Code Online (Sandbox Code Playgroud)

javascript inheritance constructor class ecmascript-6

0
推荐指数
1
解决办法
3177
查看次数