Home  >  Q&A  >  body text

How to reuse JavaScript class instances

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
 
  sayHello() {
    console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
  }
}

I can create instances like person = new Person('Alice', 30);

But in my case I need to create many instances which will finish their work and be deleted but I want to reuse the instance after their work is finished. I know there is no API like this.resetInstance() but is there any way to achieve this?

P粉463824410P粉463824410399 days ago525

reply all(1)I'll reply

  • P粉244730625

    P粉2447306252023-09-17 21:10:06

    Most of the time, it's not worth the effort. But if you want to do it, here is the code:

    class Person {
      constructor(name, age) {
        this.name = name;
        this.age = age;
      }
     
      sayHello() {
        console.log(`你好,我叫${this.name},我今年${this.age}岁。`);
      }
    
      set(name, age) {
        this.name = name;
        this.age = age;
      }
    
    }
    const person = new Person('A', 1000);
    person.sayHello(); // 你好,我叫A,我今年1000岁。
    person.set('B', 2000); 
    person.sayHello(); // 你好,我叫B,我今年2000岁。

    reply
    0
  • Cancelreply