I'm wondering if there is a standard way to re-initialize, or re-construct a class instance without creating a new instance all together.
Let's say I have a TestClass instance:
class TestClass {
constructor() {
this.x=0;
this.y=50;
this.z=200;
}
}
var testClassInstance=new TestClass();
And basically, overtime I tweak some of it's values.
testClassInstance.x+=250;
testClassInstance.y-=20;
Then later on I want to reset all of its values to whatever was defined when the instance was created. I'm wondering if there is a way to then basically reinitialize it, without creating an entirely new instance?
Is something like
testClassInstance.constructor()
safe and reliable?
class TestClass {
constructor() {
this.reset();
}
reset(){
this.x=0;
this.y=50;
this.z=200;
}
}
const myTestClass = new TestClass();
myTestClass.x = 5;
console.log(myTestClass.x); // 5
myTestClass.reset();
console.log(myTestClass.x); // 0
Your class is never modified. The class is an implementation, what you modify are the instances created using that implementation.
Look this code snippet:
class TestClass {
constructor() {
this.x=0;
this.y=50;
this.z=200;
}
}
var testClassInstance=new TestClass();
testClassInstance.x+=250;
testClassInstance.y-=20;
console.log(testClassInstance.x);
console.log(testClassInstance.y);
var anotherTestClassInstance=new TestClass();
console.log(anotherTestClassInstance.x);
console.log(anotherTestClassInstance.y);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With