简体   繁体   中英

Re-initialize a class instance without creating a new instance?

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

This answer was generated because of the first version of this question.

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); 
See? the new object has the initial values declared in TestClass's constructor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM