How to call the Base class constructor in multi-level Inheritance?

Viewed 113

I have this code and i want to call the move method of the Shape class in the Childbox class

class Shape {
    move() {
        console.log('move.');
    }
}

class Box extends Shape {
    move() {
        console.log('Box move.')
    }
}

class Childbox extends Box {
    move() {
        super.move();
        console.log('Childbox move.')
    }
}

I use super.move() it gives the box move() , so how to call the Shape class move() in the Childbox

1 Answers

You can always call arbitrary methods on your instances with call, including the move prototype method of the Shape class:

class Childbox extends Box {
    move() {
        Shape.prototype.move.call(this);
        console.log('Childbox move.')
    }
}

(In fact that's the traditional way to do super method calls, before ES6 introduced the super keyword.)

However, when you find yourself looking for something like this, I'd consider that a smell that your multi-level inheritance hierarchy is dodgy. Consider using a different design.

Related