最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Error: call super outside of class constructor - Stack Overflow

programmeradmin1浏览0评论

I try to call parent method but I get error:

Error: call super outside of class constructor

My example :

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;

I try to call parent method but I get error:

Error: call super outside of class constructor

My example :

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;
Share Improve this question asked Sep 15, 2017 at 7:31 zloctbzloctb 11.2k10 gold badges76 silver badges91 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 17

You call not the parent method, but parent constructor which is not valid call outside of the constructor. You need to use super.cool(val); instead of 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();

Use super.cool(val) instead to call the cool method on the super class. super() invokes the super class' constructor.

发布评论

评论列表(0)

  1. 暂无评论