Created
March 18, 2011 13:10
-
-
Save zela/876037 to your computer and use it in GitHub Desktop.
singletons
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
// without closure | |
function MyClass(){ | |
if (!MyClass.instance) MyClass.instance = this; | |
else return MyClass.instance; | |
} | |
var a = new MyClass, | |
b = new MyClass; | |
a === b; // true | |
// with closure (from essential js patterns book) | |
var SingletonTester = (function() | |
{ | |
//args: an object containing arguments for the singleton | |
function Singleton(args) { | |
//set args variable to args passed or empty object if none provided. | |
var args = args || {}; | |
//set the name parameter | |
this.name = 'SingletonTester'; | |
//set the value of pointX | |
this.pointX = args.pointX || 6; //get parameter from arguments or set default | |
//set the value of pointY | |
this.pointY = args.pointY || 10; | |
} | |
//this is our instance holder | |
var instance; | |
//this is an emulation of static variables and methods | |
var _static = | |
{ | |
name: 'SingletonTester', | |
//This is a method for getting an instance | |
//It returns a singleton instance of a singleton object | |
getInstance: function (args) { | |
if (instance === undefined) { | |
instance = new Singleton(args); | |
} | |
return instance; | |
} | |
}; | |
return _static; | |
})(); | |
var singletonTest = SingletonTester.getInstance({pointX: 5}); | |
console.log(singletonTest.pointX); // outputs 5 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment