扩展类并在父类中使用类属性 [英] Extending classes and using class attributes in parent class

查看:82
本文介绍了扩展类并在父类中使用类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图解决React令人讨厌的bind要求,如下所示:

I have tried to solve React's annoying bind requirement as follows:

class ExtendedComponent extends React.Component {

    custom_functions: [];

    constructor(props){
        super(props);
        let self = this;
        for (let i = 0; i < this.custom_functions.length; i++) {
            let funcname = this.custom_functions[i];
            self[funcname] = self[funcname].bind(self);
        }
    }
}

class OrderMetricsController extends ExtendedComponent {

    custom_functions: ['refreshTableOnDateChange', 'load', 'refreshTableOnTabChange'];

    constructor(props){
        super(props);
        ...

这将排除对

this.refreshTableOnDateChange = this.refreshTableOnDateChange.bind(this);

现在,我得到的问题是this.custom_functions.lengthTypeError: Cannot read property 'length' of undefined.

For now, I get TypeError: Cannot read property 'length' of undefined where the problem is this.custom_functions.length.

推荐答案

custom_functions: ['refreshTableOnDateChange', 'load', 'refreshTableOnTabChange'];

是类型注释,而this.custom_functions仍未定义.相反,它应该是一个属性初始值设定项:

is type annotation, and this.custom_functions is still undefined. Instead, it should be a property initializer:

custom_functions = ['refreshTableOnDateChange', 'load', 'refreshTableOnTabChange'];

或者考虑其静态性质,custom_functions可以是静态属性:

Or considering its static nature, custom_functions can be a static property:

static custom_functions = ['refreshTableOnDateChange', 'load', 'refreshTableOnTabChange'];

在这种情况下,它可以在构造函数中作为this.constructor.custom_functions访问.

In this case it is accessible in constructor as this.constructor.custom_functions.

bind中没有什么烦人的,这就是JS的工作方式.

There's nothing annoying in bind, this is how JS works.

对于严格的命名约定,可以遍历方法名称(例如,名称与on**Handler匹配的名称)来自动绑定方法:

For strict naming conventions, the methods can be bound automatically by traversing through method names, for example the ones which names match on* or *Handler:

const uniquePropNames = new Set([
  ...Object.getOwnPropertyNames(this),  
  ...Object.getOwnPropertyNames(this.constructor.prototype)
]);

for (const propName of uniquePropNames) {
  if (typeof this[propName] === 'function' && /^on[A-Z]|.Handler$/.test(propName)) {
     this[propName] = this[propName].bind(this);
  }
}

一个不错的选择是core-decorators 中的 @autobind装饰器.

A good alternative is @autobind decorator from core-decorators.

这篇关于扩展类并在父类中使用类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆