Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

193
Vistas
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 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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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 refers to as "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; }

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda