0

I want to create a store that implements the Singleton pattern.

class SingletonStore {
  instance = null;
  constructor(id) {
    console.log(this, 'this obj')
    if (!SingletonStore.instance) {
      this.id = id;
      SingletonStore.instance = this;
    } else {
      return SingletonStore.instance;
    }
  }
}
const emp1 = new SingletonStore(1);
const emp2 = new SingletonStore(2);

console.log("First  : ", emp1);
console.log("Second  : ", emp2);

All what i want to achieve is next: when i will call

console.log("First  : ", emp1);
console.log("Second  : ", emp2);

... in each console.log i want to get only the first instance meaning getting 2 times the store that contains {id:1}, but now the second console.log returns the {id:2} which is not correct.
NOTE: i know that i can achieve this taking outside the singleton the instance parameter.
Question: How to achive what i described above using my current implementation without creating a variable outside the singleton?

Asking
  • 3,487
  • 11
  • 51
  • 106
  • You'll need a *`static` class property* to store instances on. Currently `instance` is a property of the instance, not the class, so doesn't retain anything across calls. – deceze Oct 20 '22 at 11:40
  • @deceze, how to make `instance` as class property in my case? – Asking Oct 20 '22 at 11:42
  • `static instance` – VLAZ Oct 20 '22 at 11:54
  • @VLAZ, but if i add `static` keyword in front of `instance` nothing changed. I again get 1 and 2 as ids. Could you help? I am not sure if i understand what @deceze meant. – Asking Oct 20 '22 at 11:55
  • You also need to change `this.instance` to `SingletonStore.instance`, otherwise you're still using *the instance* (`this`) to store the attribute. – deceze Oct 20 '22 at 11:58
  • @deceze, changed, but nor result there – Asking Oct 20 '22 at 12:02
  • You forgot to change one more location… – deceze Oct 20 '22 at 12:02
  • @deceze, thanks, it works. But what is the difference between `this. instance ` and `SingletonStore.instance` ? – Asking Oct 20 '22 at 12:07
  • 1
    `this` refers to *the current instance*, which will always start out blank. Explicitly referring to the class obviously explicitly refers to the class, which can retain values independently of instances. – deceze Oct 20 '22 at 12:17

0 Answers0