Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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?

like image 500
Gage Hendy Ya Boy Avatar asked Jun 28 '26 14:06

Gage Hendy Ya Boy


2 Answers

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
like image 137
Pavlo Avatar answered Jul 01 '26 03:07

Pavlo


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.
like image 27
Ele Avatar answered Jul 01 '26 03:07

Ele