繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM