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