es6从父类的静态方法访问子类的静态方法?

eag*_*poo 2 ecmascript-6 es6-class

我想做这个:

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);
Run Code Online (Sandbox Code Playgroud)

但这不起作用。这可以通过其他方式实现吗?我不想在 Parent 中对 Child.myMethod2 进行硬编码,我知道这会起作用,因为我希望随机子类能够定义/覆盖静态方法,但在不事先知道哪个类是子类的情况下从父类调用该方法。

Est*_*ask 5

myMethod2未定义,因为代码错误。this是静态方法中的类构造函数,this.constructor是构造函数的构造函数,即Function。它应该是:

class Parent {
  static myMethod1(msg) {
    this.myMethod2(msg);
  }
}
Run Code Online (Sandbox Code Playgroud)

这是反模式,因为Parent没有myMethod2, 并且Parent.myMethod1()会导致错误。它应该包含 no-op myMethod2,或者被标记为抽象类以永远不会被直接访问。