Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Singleton pattern description is misleading #251

Open
Tomboyo opened this issue May 2, 2024 · 0 comments
Open

Singleton pattern description is misleading #251

Tomboyo opened this issue May 2, 2024 · 0 comments

Comments

@Tomboyo
Copy link

Tomboyo commented May 2, 2024

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"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant