Skip to content

Instantly share code, notes, and snippets.

@zhuochun
Created June 15, 2012 04:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhuochun/2934678 to your computer and use it in GitHub Desktop.
Save zhuochun/2934678 to your computer and use it in GitHub Desktop.
Singleton JavaScript Pattern
// http://kaijaeger.com/articles/the-singleton-design-pattern-in-javascript.html
var Singleton = (function() {
var instance = null;
function PrivateConstructor() {
var rand = Math.round(Math.random() * 100);
this.getRand = function() {
return rand;
}
}
return new function() {
this.getInstance = function() {
if (instance == null) {
instance = new PrivateConstructor();
instance.constructor = null;
}
return instance;
}
}
})();
var singletonInstance = Singleton.getInstance();
// =============================
// In a remotely aspect oriented kind of way, you could even do this:
// =============================
var global = this;
function singletonify(constructorName) {
var constructorFunc = global[constructorName];
var instance = null;
global[constructorName] = new function() {
this.getInstance = function() {
if (instance == null) {
instance = new constructorFunc();
instance.constructor = null;
}
return instance;
}
}
}
function RegularConstructor() {
var rand = Math.round(Math.random() * 100);
this.getRand = function() {
return rand;
}
}
singletonify("RegularConstructor");
var myInstance = RegularConstructor.getInstance();
document.write(myInstance.getRand());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment