如果我按如下方式定义两个类......
class A {
getParentInstance(...args) {
return new super.constructor(...args);
}
}
class B extends A {}
console.log((new B).getParentInstance().constructor.name);
Object
已记录到控制台,而不是我想要的A
。这是因为super
A.prototype.getParentInstance
引用了A
的超类,具体是Object
。这与super
相对于原型链中的当前级别的替代方案 - B
A
相反。
我的问题是:有没有办法定义方法,以便在继承时在原型链的每个级别使用 relative super?有效地导致......
(new B).getParentInstance().constructor.name === 'A'
答案 0 :(得分:0)
你可以试试这样的事情
class A {
static getParentConstructor() {
return Object;
}
}
class B extends A {
static getParentConstructor() {
return A;
}
}
var b = new B();
var a = new (b.constructor.getParentConstructor())();
答案 1 :(得分:0)
一点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);
导致正确的"超级"被抓住,因此根据需要记录'A'
。