Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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. */
  }
  
  getName(){
    return this.name;
  }
  
  getCity(){
    return this.objectB.getCity(); /* This method provides access to the define method in class B. */
  }
}

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

objectA = new A('john', 'london');
console.log('Name: ', objectA.getName());
console.log('City:', objectA.getCity());
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading