【问题标题】:javaScript, react-native, super.method is undefinedjavaScript、react-native、super.method 未定义
【发布时间】:2021-10-05 01:17:12
【问题描述】:

反应原生。在子类中, super.method 未定义。为什么父类方法在super中不可见?

export class ParentClass {
    constructor(field) {
        this.field = field;
    }

    protected ruleMatch = (type: string): string => {
        return type;
    }

    onGetRule = (type: string) => {
        return this.ruleMatch(type);
    }
}

export class ChildrenClass extends ParentClass {
    // extends method of parent Class
    onGetRule = (type: string) => {
        if(type === 'typeA') {
            return 'anything';
        }
        return super.onGetRule(type); // TypeError: Cannot read property 'call' of undefined
    }
}

【问题讨论】:

标签: javascript class extends


【解决方案1】:

您将方法onGetRule 定义为字段声明。将onGetRule-method 的语法改为

export class ParentClass {
    constructor(field) {
        this.field = field;
    }

    protected ruleMatch = (type: string): string => {
        return type;
    }

    onGetRule(type: string) {
        return this.ruleMatch(type);
    }
}

export class ChildrenClass extends ParentClass {
    // extends method of parent Class
    onGetRule(type: string) {
        if(type === 'typeA') {
            return 'anything';
        }
        return super.onGetRule(type); // TypeError: Cannot read property 'call' of undefined
    }
}

字段声明在每个类实例上创建道具,而不是像类方法那样使用原型链。

是这样的:

class ParentClass {
  constructor(field) {
    this.field = field;
    this.onGetRule = (type) => {
        return type;
    }
  }
}

所以super.onGetRule 将是未定义的,因为它在原型链中丢失了。

【讨论】:

  • 不客气。如果有帮助,请将答案标记为已接受。谢谢!
猜你喜欢
  • 2021-09-15
  • 2016-09-26
  • 2022-01-21
  • 2021-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多