错误:在类构造函数之外调用super

zlo*_*ctb 2 javascript ecmascript-6

我尝试调用父方法,但我得到错误:

错误:在类构造函数之外调用super

我的例子:

class xo{
    cool(x){
        console.log(`parent init${x}`)
    }
}
class boo extends xo{
    cool(val){
        super(val);
        console.log(`child init${x}`)
    }
}

x = new boo;
Run Code Online (Sandbox Code Playgroud)

Sur*_*yan 11

您调用的不是父方法,而是在构造函数之外调用无效的父构造函数.你需要用super.cool(val);而不是super(val);

class xo{

    cool(x) {
        console.log(`parent init${x}`)
    }

}

class boo extends xo {

    cool(val) {
        super.cool(val);
        console.log(`child init${x}`)
    }

}

x = new boo();
Run Code Online (Sandbox Code Playgroud)


Gre*_*egL 4

而是使用super.cool(val)来调用cool超类上的方法。super()调用超类的构造函数。