I was trying to make a small class, make a global variable inside the class and assign them a object. Inside the class inside methods i wanted to catch this values, works with them but the main object which i declared at the top i wanted to stay as it was initialized
Example Code
class testClass {
myVarObject;
constructor() { }
methodOne() {
this.myVarObject = {
blo : 7
}
return this;
}
methodTwo() {
const testVar = this.getMyObject();
testVar.blo = 12;
return this;
}
getMyObject() {
return this.myVarObject;
}
}
let myObject = new testClass();
myObject.methodOne().methodTwo();
console.log(myObject.getMyObject());
The output of the console debug is:
Object { blo: 12 }
blo: 12
<prototype>: Object { … }
debugger eval code:31:9
What i do not understand:
Why this.myVarObject.blo is now 12 and not 7? I didn't modified this.myVarObject but only testVar.blo . I am bit confused :)
When i modify my Variable "testVar" inside the Method "methodTwo", how i can prevent that "this.myVarObject" is overtaking this new values automatically? What i wanted to do with
testVar = this.getMyObject();
is to make a copy, modify it and return it as a result. But the main Variable (this.myVarObject) must stay as it is
What i have missed?
Thank you for your help