有没有办法让 super 相对于子类?

Is there a way to keep super relative to the subclass?

如果我定义两个类如下...

class A {
  getParentInstance(...args) {
    return new super.constructor(...args);
  }
}

class B extends A {}

console.log((new B).getParentInstance().constructor.name);

Object 被记录到控制台,而不是我想要的 A。这是由于 A.prototype.getParentInstance 中的 super 引用了 A 的超类,具体是 Object。这与替代方案相反,替代方案是 super 相对于原型链中的当前级别——对于 B,即 A

我的问题是:有没有一种方法可以在继承时在原型链的每一层使用relative super 来定义方法?有效地导致...

(new B).getParentInstance().constructor.name === 'A'

你可以试试这样的

class A {
  static getParentConstructor() {
    return Object;
  }
}

class B extends A {
  static getParentConstructor() {
    return A;
  }
}

var b = new B();
var a = new (b.constructor.getParentConstructor())();

有点Object.getPrototypeOf()魔术似乎是诀窍:

class A {
  getParentInstance(...args) {
    const thisProto = this.constructor.prototype;
    const RelativeSuperConstructor = Object.getPrototypeOf(thisProto).constructor;
    return new RelativeSuperConstructor(...args);
  }
}

class B extends A {}

console.log((new B).getParentInstance().constructor.name);

导致正确的 "super" 被抓取,因此根据需要记录 'A'