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

标签 javascript es6-class

我的用例是 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

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/

相关文章:

javascript - JS 类属性验证函数返回 bool 值?

javascript - 基于 ES6 类的继承是否与 es5 原型(prototype)继承相同

javascript - rxjs - 具有下一个和错误回调的运算符?

javascript - CSS 用省略号填充表 TD 内的空白

javascript 使用正则表达式测试字母、数字、空格和破折号

javascript - 获取 ES6 类的 "this"调用方法并获取数据成员

javascript - 如何使用 Jest 在 ES6 类方法中测试对 redux 存储的调度?

javascript - 令人困惑的 webpack/ES6 项目设置

javascript - appendChild 在 IE 中无法正常工作

javascript - Vuejs : Can't pass object to web component using v-bind