Home > Software design >  If a class contains a reference to another class, can I access the initial class from the nested cla
If a class contains a reference to another class, can I access the initial class from the nested cla

Time:01-10

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?

CodePudding user response:

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);

  •  Tags:  
  • Related