Created
February 5, 2012 16:48
-
-
Save calvinfroedge/1746528 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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