I have two classes, A
and B
. I will only be setting the values of class A
and I want class B
variables to hold the same value as class A or have have access to all values of class A
variables. In my case, class A and B should not be inherited logically. Is this possible without inheritance?.
In the below code, I have given an example where I need the value of only one variable and I could have passed the name
as a method param. But, in my actual project I need to set the value of 20+ variables and it is not easy to pass around 20+ values to another class.
class B {
name: string
age: number
print() {
console.log(this.name);
}
}
const b = new B();
class A {
name: string;
age: number;
printValues() {
b.print()
}
}
const a = new A();
a.name = "TOM"
a.printValues() // Want to Print TOM
2
Answers
A
should have a property that links it to aB
instance. Then you can use a setter to pass thename
assignment through.You can simultaneously assign values to both instances with
Proxy
:But better save
b
in thea
instance with the A’s constructor argument or createb
in the A’s constructor.