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?