You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The answer to question one lists a handful of ways to create objects. One of the ways given is the singleton pattern (emphasis mine):
Singleton pattern:
A Singleton is an object which can only be instantiated one time. Repeated calls to its constructor return the same instance. This way one can ensure that they don't accidentally create multiple instances.
var object = new (function () {
this.name = "Sudheer";
})();
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:
varobject=new(functionSingleton(){this.name="Sudheer";})();// Instantiate a second instancevarobject2=new(object.constructor);object===object2// falseObject.getPrototypeOf(object)===Object.getPrototypeOf(object2)// trueobject2.constructor// function Singleton()object2.name// "Sudheer"
The text was updated successfully, but these errors were encountered:
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
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:
The text was updated successfully, but these errors were encountered: