Open Tomboyo opened 6 months ago
class Singleton { constructor() { if (Singleton.instance) { return Singleton.instance; }
this.name = "Sudheer"; // You can define properties or methods as required.
Singleton.instance = this; // Store the instance.
return this; // Return the instance.
}
}
const object1 = new Singleton(); console.log(object1.name); // Outputs: Sudheer
const object2 = new Singleton(); console.log(object2.name); // Outputs: Sudheer
console.log(object1 === object2); // true
The answer to question one lists a handful of ways to create objects. One of the ways given is the singleton pattern (emphasis mine):
The problem with this description is that it is entirely possible to instantiate a second distinct instance from the constructor function. In other words, repeated calls to the constructor function will return different instances. Consider the following: