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

6

u/MonsterMook Senior UI Jan 13 '14

{}

Why did you guys waste so many characters?

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.

1

u/cwmma Jan 13 '14

If you did Object.create instead of object literal notation it would have a prototype.

If we're going all out for over engineering an iife

2

u/cwmma Jan 13 '14

Disclaimer you more or less never need to create a singletons, and if you did your method (or any that didn't involve prototype) wouldn't give much of a benefit over an object literal, but you could also try

var createSun = (function(){

    var sun;
    return function(){
            if(sun){
                   return sun;
            }
            var privateMass = 10000000000; //private
            var looseMass = function(mass){
             privateMass -= mass;    
            };
            var publicEmitLight = function(){
                  //some complex Nuclear fission 
                  //calling looseMass()
                  looseMass(10);
            };
            var getMass = function(){
                  return privateMass;
            };
            function Sun(){}
            Sun.prototype = {
                emitLight: publicEmitLight,
                getMass: getMass
            };
           sun = new Sun;
       return sun;
};
}())

as this would allow sub classes of your singleton.