0

React-native. In child class, super.method is undefined. Why is the parent class method not visible in the 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
    }
}
Guillaume Georges
  • 3,878
  • 3
  • 14
  • 32
Alex Mazur
  • 21
  • 1
  • Does this answer your question? [How do I override inherited methods when using JavaScript ES6/ES2015 subclassing](https://stackoverflow.com/questions/39886830/how-do-i-override-inherited-methods-when-using-javascript-es6-es2015-subclassing) – Guillaume Georges Jul 29 '21 at 12:19

1 Answers1

0

You defined your method onGetRule as field declaration. Change the syntax of onGetRule-method to

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
    }
}

A field declarations create the prop on each class instance, rather than using the prototype-chain like class-methods.

It's like this:

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

and so super.onGetRule will be undefined, because it's missing in the prototype-chain.

wuarmin
  • 3,274
  • 3
  • 18
  • 31