我的用例是 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
andsuper[expr]
expressions are valid in any method definition in both classes and object literals.Syntax
super([arguments]); // calls the parent constructor. super.functionOnParent([arguments]);
演示:
class Super {
componentWillMount() {
console.log('parent')
}
}
class Sub extends Super {
componentWillMount() {
super.componentWillMount()
console.log('child')
}
}
new Sub().componentWillMount();
关于javascript - 覆盖父类实例(非静态)方法javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46245987/