Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding a parent class instance (non-static) method javascript

My use case is React, but this is a JavaScript question.

I'd like to extend the functionality of componentWillMount by using a subclass. How can I accomplish this?

class Super {
    componentWillMount() {
        doStuff()
    }
}
class Sub extends Super {
    componentWillMount() {
        super() // this doesn't work
        doMoreStuff()
    }
}
like image 262
Gabe Rogan Avatar asked Sep 15 '17 19:09

Gabe Rogan


1 Answers

The syntax to use is:

super.componentWillMount()

From mdn:

The super keyword is used to call functions on an object's parent.

The super.prop and super[expr] expressions are valid in any method definition in both classes and object literals.

Syntax

super([arguments]); // calls the parent constructor.
super.functionOnParent([arguments]);

Demo:

class Super {
    componentWillMount() {
        console.log('parent')
    }
}

class Sub extends Super {
    componentWillMount() {
        super.componentWillMount()
        console.log('child')
    }
}

new Sub().componentWillMount();
like image 194
trincot Avatar answered Oct 03 '22 19:10

trincot