Skip to content

Instantly share code, notes, and snippets.

@calvinfroedge
Created February 5, 2012 16:48
Show Gist options
  • Save calvinfroedge/1746528 to your computer and use it in GitHub Desktop.
Save calvinfroedge/1746528 to your computer and use it in GitHub Desktop.
//This technique was invented by Kai Jaeger (http://kaijaeger.com/articles/the-singleton-design-pattern-in-javascript.html), I'm just showing an implementation
var Singleton = (function()
{
var instance = false;
/*
* Because this is in a closure, it cannot be accessed
*/
var member = 'test';
function Constructor(){
this.getMember = function(){
return member;
}
this.setMember = function(v){
member = v;
}
}
/*
* This is what's actually returned by the closure
*/
return new function(){
this.getInstance = function() {
/*
* Private member functions are accessible once the constructor has been called
*/
if(instance == false){
instance = new Constructor();
instance.constructor = null;
}
return instance;
}
}
}
)();
//print(Singleton.getInstance().getRand());
Singleton.getInstance().setMember('whatuppppp');
print(Singleton.getInstance().getMember());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment