javascript-interview-questions icon indicating copy to clipboard operation
javascript-interview-questions copied to clipboard

Singleton pattern description is misleading

Open Tomboyo opened this issue 1 year ago • 1 comments

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:

var object = new (function Singleton() {
  this.name = "Sudheer";
})();

// Instantiate a second instance
var object2 = new (object.constructor);

object === object2 // false
Object.getPrototypeOf(object) === Object.getPrototypeOf(object2) // true
object2.constructor // function Singleton()
object2.name // "Sudheer"

Tomboyo avatar May 02 '24 23:05 Tomboyo

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

harshu-789 avatar Oct 07 '24 07:10 harshu-789

@Tomboyo @harshu-789 Thank you for your feedback. I updated the answer.

sudheerj avatar May 18 '25 11:05 sudheerj