Skip to content

Singleton pattern description is misleading #251

Closed
@Tomboyo

Description

@Tomboyo

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"

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions