Overriding the instance method of the parent class (non-static) javascript

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

I would like to extend functionality componentWillMountwith a subclass. How can i do this?

class Super {
    componentWillMount() {
        doStuff()
    }
}
class Sub extends Super {
    componentWillMount() {
        super() // this doesn't work
        doMoreStuff()
    }
}
+4
source share
2 answers

The syntax to use is:

super.componentWillMount()

From mdn :

The keyword is superused to call the functions of the parent object.

The expressions super.propand are super[expr]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();
Run codeHide result
+3
source

From the reaction of the documents:

, ? Facebook React , - , .

, . , , , .

, UI, , JavaScript. , , .

https://facebook.imtqy.com/react/docs/composition-vs-inheritance.html

+1

Source: https://habr.com/ru/post/1685773/


All Articles