Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

306
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!