skip to Main Content
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 instance as person = new Person('Alice', 30);

But in my case i need to create many instances which will do their work and gets removed, but i want to reuse that instance once its work is done.
I know there is no api like this.resetInstance() but is there any way to achieve this?

2

Answers


  1. It most cases it does not worth the effort. But, if you want to do it, here you go:

    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.`);
      }
    
      set(name, age) {
        this.name = name;
        this.age = age;
      }
    
    }
    const person = new Person('A', 1000);
    person.sayHello(); // Hello, my name is A and I'm 1000 years old.
    person.set('B', 2000); 
    person.sayHello(); // Hello, my name is B and I'm 2000 years old.
    
    Login or Signup to reply.
  2. Just make a cache.

    class Person {
      constructor(name, age) {
        console.log('Person constructor run')
        this.name = name;
        this.age = age;
      }
      sayHello() {
        console.log(`Hello, my name is ${this.name} and I'm ${this.age} years old.`);
      }
    }
    const instanceCache = {};
    function getInstance(name,age) {
      if(!instanceCache[`${name}${age}`]){
        instanceCache[`${name}${age}`] =  new Person(name,age);
      }
      return instanceCache[`${name}${age}`];
    }
    
    const p1 = getInstance('Jack', 18);
    const p2 = getInstance('Jack', 18);
    const p3 = getInstance('Bob', 20);
    console.log(p1 === p2); // true
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search