簡體   English   中英

重新初始化類實例而不創建新實例?

[英]Re-initialize a class instance without creating a new instance?

我想知道是否存在一種標准的方法來重新初始化或重新構造類實例,而無需一起創建新實例。

假設我有一個TestClass實例:

class TestClass {
  constructor() {
    this.x=0;
    this.y=50;
    this.z=200;
  }
}

var testClassInstance=new TestClass();

基本上,加班我會調整一些價值觀。

testClassInstance.x+=250;
testClassInstance.y-=20;

然后,稍后我想將其所有值重置為創建實例時定義的值。 我想知道是否有一種方法可以在不創建全新實例的情況下對其進行重新初始化?

是這樣的

testClassInstance.constructor()

安全可靠嗎?

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

產生此答案的原因是此問題的第一個版本。

您的課程永遠不會被修改。 該類是一個實現,您修改的是使用該實現創建的實例。

請看以下代碼片段:

 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); 
看到? 新對象具有在TestClass的構造函數中聲明的初始值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM