Home > Back-end >  How to access the properties of a another class in a nested class in javascript
How to access the properties of a another class in a nested class in javascript

Time:01-02

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?

CodePudding user response:

The parent-child relationship has to be established and maintained explicitly for each child. And since the parent property of each child instance/object is just a reference to a Parent instance, the OP does not need to worry about memory consumption or whatever it is, the OP does call "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; }

  • Related