我有兩個類,父類和子類,我希望子類以某種方式訪問??父類上的方法(請注意,子類不會擴展/繼承父類)......父類只有一個屬性它的子物件陣列。
class Parent {
constructor() {
this.name = "parent";
this.children = [];
}
addChild(child) {
this.children.push(child);
}
foo() {
console.log("foo");
}
}
class Child {
constructor(name) {
this.name = name;
// Call the foo function of the parent
}
}
我還發現了另一種方法:
class Child {
constructor(name, parent) {
this.name = name;
this.parent = parent;
this.parent.foo();
}
}
但是在上面的方法中,每個孩子都有它的父類作為它的一個屬性,但是父類也有子屬性,所以,它會造成這樣一種情況,即孩子包含父類,父類又包含子類,而父類又包含父類,所以..... 而且我不認為在物件上擁有無限嵌套的屬性是最好的編程實踐,所以我對這種方法有點猶豫。
我希望有其他方法可以做到這一點,或者無限嵌套的屬性方法好嗎?
uj5u.com熱心網友回復:
必須為每個孩子明確地建立和維護父子關系。并且由于parent每個子實體/物件的屬性只是對Parent實體的參考,因此 OP 無需擔心記憶體消耗或其他任何內容,OP 將其稱為"nested"。
class Child {
constructor(name, parent) {
this.name = name;
this.parent = parent;
// Call the `foo` function of the parent
// in case `parent.foo` exists and is callable.
parent?.foo?.();
}
}
class Parent {
constructor() {
this.name = 'parent';
this.children = [];
}
addChild(referenceOrName) {
if (typeof referenceOrName === 'string') {
this.children.push(new Child(referenceOrName, this));
} else if (
(referenceOrName instanceof Child) &&
!this.children.includes(referenceOrName)
//!this.children.find(child => child.name === referenceOrName.name)
) {
referenceOrName.parent = this;
this.children.push(referenceOrName);
}
}
foo() {
console.log("foo");
}
}
const testParent = new Parent;
const testChild = new Child('baz', testParent);
console.log({ testParent });
testParent.addChild('bar');
testParent.addChild(testChild);
console.log({ testParent });
testParent.addChild('biz');
testParent.addChild('boz');
console.log({ testParent });
.as-console-wrapper { min-height: 100%!important; top: 0; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/401253.html
標籤:javascript 班级 目的 哎呀 遗产
上一篇:從同一個父類的另一個類訪問物件
