I have this code here: what I am trying to do is call function 'counterAdder' that lives in class A from the class B.
Then I am supposed to create an instance of A and an instance of B, then call the 'counterAdder' function which updates the instance of A's 'counter' item.
When I run this code, it outputs as 0 but I need 1.
class A {
constructor(){
this.counter = 0;
}
}
class B{
constructor(){
}
counterAdder(){
A.counter =1;
}
}
const a = new A();
const b = new B();
b.counterAdder();
console.log(a.counter) // => 1
I can't seem to figure out how to get 'a' to update when an action from 'b' is run.
I am unable to modify anything outside of class A and class B and only using pure JavaScript.
CodePudding user response:
The following code:
counterAdder(){
A.counter =1;
}
does not do what you are trying to do. Instead it adds a new property (or something else, I'm not exactly sure why it even works in the first place). What you want to do is modify the counter of a
, the variable you assigned to A
. So instead do this:
counterAdder(){
a.counter =1;
}