如何在 javascript 中的嵌套 class 中访问另一个 class 的属性

How to access the properties of a another class in a nested class in javascript

我有两个 class,parent 和 child,我希望 child class 访问 [=39= 上的方法] class 以某种方式(注意 child class 不 extend/inherit 来自 parent class)... parent class 只是有一个 属性 的数组 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
  }

}

我还发现了另一种方法:

class Child {
  constructor(name, parent) {
    this.name = name;
    this.parent = parent;
    this.parent.foo();
  }
}

但在上述方法中,每个 child 都有其 parent class 作为其上的 属性 但 parent class也有 child 属性 所以,它会造成 child 包含 parent 的情况,其中 child 又包含 parent 等等..... 而且我不认为在 object 上拥有无限嵌套的属性是最好的编程实践,所以我对这种方法有点犹豫。

我希望有其他方法可以做到这一点,或者无限嵌套 属性 方法可以吗?

必须为每个 child 显式建立和维护 parent-child 关系。由于每个 child instance/object 的 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; }