#javascript
#nodejs
I have 3 classes (A, B, C) in my script. Class B extends class A and inside class B is a method which calls a new instance of class C.
Sample Code:
// First class
class A {
constructor() {
this.name = 'Eve';
}
getName() {
return this.name;
}
}
class B extends A {
constructor(age) {
this.age = age;
}
getAge() {
return this.age;
}
getC() {
// This is where I needed a solution
return new C();
}
}
class C {
constructor() {
this.address = 'Market Village';
}
getAllInfo() {
return this;
}
}
The expected output if run the code below is what it should be:
let b = new B(18);
let info = b.getC().getInfo();
console.log(info); // {address: 'Market Village'}
But what I wanted to happen is for class C to inherit all properties and methods of class A and B so that class C is able to use the properties and methods of both classes.
I've tried several approaches but none works.
Attempt #1:This approach injects all the properties and methods of class A and B into class C but the problem is it throws an error saying cannot set ... of undefined
, for some reason, the methods of class C are not read:
getC() {
C.calls(this);
}
Attempt #2
This approach reads all the methods of class C and injects all the properties of both class A and B but not its methods. So again, when you call any of the methods of class A and B inside class C, it throws an error:
getC() {
let _classC = new C();
Object.assign( _classC, this );
return _classC;
}
Is there a way to call a new instance of class C and inject all the properties and methods of class B and A?
Note that class C must be a standalone class and should not extend either classes.
Any help is greatly appreciated.