简体   繁体   English

重新初始化类实例而不创建新实例?

[英]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: 假设我有一个TestClass实例:

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. 新对象具有在TestClass的构造函数中声明的初始值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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