-1

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
4

2 回答 2

2

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:

(function(ns, window, undefined) {
    ns.singleton = {
        bang: 'Big'
    };

    window.ns = ns;
})(ns || {}, window);

console.log(window.ns.singleton.bang === 'Big');

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

于 2012-11-15T06:07:45.870 回答
0

Your code is messy.

I would use this pattern:

var universe = function(){

  var bang = "Big"; //private variable

  // defined private functions here    

  return{  //return the singleton object 
    everything : true,
    // or nothing : true, I don't guess your logic

    // public functions here (closures accessing private functions and private variables)
    getBang : function(){ return bang; } 
  };
}();

You can then call for example:

alert(universe.everything); // true
alert(universe.getBang()); //true
alert(universe.bang); //Undefined property ! Cause private ;)

Since, it's a singleton, there's no need to define share methods to prototype object because there would be one instance. (hence the function expression and not function declaration).

All the beauty of this design is the benefit of scope chain and closures (public functions).

于 2012-11-16T13:20:05.710 回答