I’m reading Javascript Patterns recently.And I don’t understand the code below when it talks about singleton pattern:
function Universe(){
var instance;
Universe=function Universe(){
return instance;
};
Universe.prototype=this;
//the new Universe below,refers to which one?The original one,
//or the one:function(){return this;} ??
instance=new Universe();
instance.constructor=Universe;
instance.bang="Big";
return instance;
}
Universe.prototype.nothing=true;
var uni=new Universe();
Universe.prototype.everything=true;
var uni2=new Universe();
uni===uni2;//true
Not much going on here. The main focus should be on the constructor, it is returning an instantiated Universe for you. So anyone that calls it will have a reference to the same instance. Notice how the constructor is pointing to the Universe function.
I wouldn’t use this pattern, as the new keyword implies a new instance is being created, and it seems a little too esoteric for my taste. In JS you can perfectly just have an object literal, often used with a namespace pattern:
Granted, this isn’t a true singleton, but it does not need to be instantiated, and anyone who uses it will have the same values.
For more singleton implementations, see Javascript: best Singleton pattern