Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.