[英]How to access the properties of a another class in a nested class in javascript
I have two classes, parent and child and I want the child class to access a method on the parent class in some way (note that child class doesn't extend/inherit from parent class)... The parent class just has a property它的子對象數組。
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();
}
}
但是在上述方法中,每個孩子都有其父 class 作為其上的屬性,但父 class 也具有子屬性,因此,它會造成子包含包含子的父的情況,該子包含再次包含父的子,因此on..... 而且我認為在 object 上擁有無限嵌套的屬性並不是最好的編程實踐,所以我對這種方法有點猶豫。
我希望有其他方法可以做到這一點,或者無限嵌套的屬性方法可以嗎?
必須為每個孩子明確地建立和維護父子關系。 由於每個子實例/對象的parent
屬性只是對Parent
實例的引用,因此 OP 不需要擔心 memory 消耗或其他任何東西,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; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.