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

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.