r/javascript • • Jan 13 '14

How to create Singleton objects in JavaScript

http://viralpatel.net/blogs/javascript-singleton-design-pattern/
0 Upvotes

6 comments sorted by

View all comments

9

u/[deleted] Jan 13 '14 edited Jan 13 '14

Ahem...

var singleton = (function() {
  var privateData = "foo";
  var privilegedMethod = function() {
    return privateData;
  };

  var why = {
    not: "just",
    create: "a",
    literal: "object",
    with: privilegedMethod
  };

  return why;
}());

console.log(singleton.privateData); // => undefined
console.log(singleton.with()); // => "foo"

4

u/OverZealousCreations Jan 13 '14

This is much better. The original is another case of someone forcing a pure OOP design pattern onto JavaScript's much lighter Object-only design.

(The only drawback is if you want lazy initialization...)

3

u/[deleted] Jan 13 '14 edited Jan 13 '14

Exactly. There's simply no need for the classical singleton (oxymoron) pattern in JavaScript, because we have object literals and IIFE closures. What's great about this IIFE is we can remove two characters and it becomes a factory. That's how we achieve lazy initialization - an object should not control its own creation and lifetime.

The common singleton pattern is nothing more than a hack for class-based system that violates a few OOP principles. Look at the problem singletons try to solve - they ensure that a given class can only have one instance at any given time... But we don't have classes in JavaScript! Just objects. No problem to solve.

And remember that even if you create a singleton like this, someone can always do _.clone(singleton), though the two object will share private scopes and you'll wish you just started with a plain old object literal.