编程语言
首页 > 编程语言> > 覆盖父类实例(非静态)方法javascript

覆盖父类实例(非静态)方法javascript

作者:互联网

我的用例是React,但这是一个JavaScript问题.

我想通过使用子类来扩展componentWillMount的功能.我怎么能做到这一点?

class Super {
    componentWillMount() {
        doStuff()
    }
}
class Sub extends Super {
    componentWillMount() {
        super() // this doesn't work
        doMoreStuff()
    }
}

解决方法:

要使用的语法是:

super.componentWillMount()

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

06001

演示:

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

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

new Sub().componentWillMount();

标签:javascript,es6-class
来源: https://codeday.me/bug/20190622/1264142.html