zloctb
zloctb

Reputation: 11186

Error: call super outside of class constructor

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;

Upvotes: 5

Views: 7905

Answers (2)

Suren Srapyan
Suren Srapyan

Reputation: 68655

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();

Upvotes: 17

GregL
GregL

Reputation: 38121

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

Upvotes: 4

Related Questions