eagspoo
eagspoo

Reputation: 2135

es6 access static method of child class from static method of parent?

I want to do this:

class Parent {
    static myMethod1(msg) {
    // myMethod2 is undefined
    this.constructor.myMethod2(msg);
  }
}

class Child extends Parent {
  static myMethod2(msg) {
    console.log('static', msg);
  }
}

Child.myMethod1(1);

But it doesn't work. Is this possible some other way? I don't want to hard code Child.myMethod2 in Parent which I know would work since I want random child classes to be able to define/override the static method but call that method from the parent without prior knowledge of which class is the child.

Upvotes: 2

Views: 1043

Answers (1)

Estus Flask
Estus Flask

Reputation: 223164

myMethod2 is undefined because the code is wrong. this is class constructor in static methods, and this.constructor is the constructor of a constructor, i.e. Function. It should be:

class Parent {
  static myMethod1(msg) {
    this.myMethod2(msg);
  }
}

This is antipattern, because Parent doesn't have myMethod2, and Parent.myMethod1() will result in error. It should either contain no-op myMethod2, or be labeled as abstract class to never be accessed directly.

Upvotes: 5

Related Questions