我怎样才能像在派生类上定义的那样调用超类方法



我有这些类:

class Control {
get code() {
return 3;
}
getCodeChain() {
var result = [this.code];
if (super.getCodeChain) {
result = result.concat(super.getCodeChain());
}
return result;
}
}
class SubControl extends Control {
get code() {
return 2;
}
}
class AnotherControl extends SubControl {
get code() {
return 1;
}
}
console.log((new AnotherControl()).getCodeChain()); // prints 1

当我在AnotherControl实例上调用getCodeChain时,它一直到Control上下文,因此递归会忽略AnotherControl和SubControl上下文。

我需要得到CodeChain,但我不想/不能在所有子类中实现getCodeChain()方法。我期望的结果是[1,2,3]。

我怎样才能像在派生类上定义的那样调用超类方法?

您可以使用Object.getPrototypeOf:遵循原型链

class Control {
get code() { return 3; }
getCodeChain() {
const result = [];
for (let proto = Object.getPrototypeOf(this); Object.hasOwn(proto, "code"); proto = Object.getPrototypeOf(proto)) {
result.push(proto.code);
}
return result;
}
}
class SubControl extends Control {
get code() { return 2; }
}
class AnotherControl extends SubControl {
get code() { return 1; }
}
console.log((new AnotherControl()).getCodeChain()); // [1, 2, 3]

super关键字仅适用于重写的方法。即使这样,它也会调用当前实例(this(上的超级方法,因此访问其他属性(.code(将再次解决子类上的问题。

你真正想要的更像

class Control {
get codeChain() {
return [3];
}
}
class SubControl extends Control {
get codeChain() {
return [2, ...super.codeChain];
}
}
class AnotherControl extends SubControl {
get codeChain() {
return [1, ...super.codeChain];
}
}
console.log((new AnotherControl()).codeChain); // prints [1, 2, 3]

最新更新