我有這些課程:
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]。
如何呼叫派生類上定義的超類方法?
uj5u.com熱心網友回復:
您可以使用以下原型鏈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]
uj5u.com熱心網友回復:
該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]
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/513524.html
