[Singleton]
JavaScript doesn't have classes, so the verbatim definition for singleton doesn't technically make sense.
// what we want is
var uni = new Universe();
var uni2 = new Universe();
uni === uni2; // trueInstance in a Static Property
function Universe() {
// do we have an existing instance?
if (typeof Universe.instance === "object") {
return Universe.instance;
}
// proceed as normal
this.start_time = 0;
this.bang = "Big";
// cache
Universe.instance = this;
// implicit return:
// return this;
}The drawback of above code is that instance is public. Other code may change it by mistake.
Instance in a Closure
function Unvierse() {
// the cached instance
var instance = this;
// proceed as normal
this.start_time = 0;
this.bang = "Big";
// rewrite the constructor
Universe = function () {
return instance;
};
}
The drawback is property added to Universe between initial definition and redefinition will lose. Also the constructor of created instance is not the same as Universe.
Alternative implementation
function Universe() {
// the cached instance
var instance;
// rewrite the constructor
Universe = function Universe() {
return instance;
};
// carry over the prototype properties
Universe.prototype = this;
// the instance
instance = new Universe();
// reset the constructor pointer
instance.constructor = Universe;
// all the functionality
instance.start_time = 0;
instance.bang = "Big";
return instance;
}
0 comments:
張貼意見