![](/img/trans.png)
[英]Make an instance of a class that is in an another file without creating a new variable
[英]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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.