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 of the array of it's children objects.
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
}
}
I also discovered an alternative approach:
class Child {
constructor(name, parent) {
this.name = name;
this.parent = parent;
this.parent.foo();
}
}
But in the above approach, each child has its parent class as a property on it but the parent class also has the child property so, it would create a situation where the child contains the parent which contains the child which again contains the parent and so on..... And I don't think that it is the best programming practice to have infinitely nested properties on an object, So I'm a bit hesitant to this approach.
I hope there is some other way to doing this, or is the infinitely nested property approach fine?
Childclass should have been defined under theParentclass.