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

302
Vistas
If a class contains a reference to another class, can I access the initial class from the nested class?

I'm currently trying to get more experience with Javascript classes, but I can't quite figure out if what I'm trying to achieve is possible.

Here's a simplified version of my code.

class A {

  name = "ClassA"

  classB = new B()

}

class B {

  calledFromA() {
    // Is there any way I can print "ClassA" here?
  }

}

const classA = new A();
classA.classB.calledFromA();

Class A creates a new class B. Then, from an instance of class A, I would like to call the calledFromA method and for it to be able to access everything inside "Class A".

I assume there must be a way of using this to do this?

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

0

By defining a B object in class A, methods and data members of class B can be accessed.

class A {
  name = 'empty';
  objectB = null;                  /* Object B is defined as a data member. */
  
  constructor(name, city){
    this.name = name;
    this.objectB = new B(city);    /* Object B is initialized using the constructor. */
  }
}

class B {
  city = 'empty';
  
  constructor(city)
  {
    this.city = city;
  }
}

objectA = new A('john', 'london');
console.log('Name: ', objectA.name);
console.log('City: ', objectA.objectB.city);

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