Created
February 8, 2015 12:00
-
-
Save FGRibreau/1f89ba04d4d3ab7e3e1b to your computer and use it in GitHub Desktop.
Addy Osmani - Essential JavaScript Design Patterns - Singleton issue
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 "SingletonTester" is not a valid Singleton because: | |
var InnerConstructor = SingletonTester.getInstance({ | |
pointX: 5 | |
}).constructor; | |
console.log(new InnerConstructor() !== new InnerConstructor()); // true |
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
// From http://addyosmani.com/resources/essentialjsdesignpatterns/book/#singletonpatternjavascript | |
var SingletonTester = (function () { | |
// options: an object containing configuration options for the singleton | |
// e.g var options = { name: "test", pointX: 5}; | |
function Singleton( options ) { | |
// set options to the options supplied | |
// or an empty object if none are provided | |
options = options || {}; | |
// set some properties for our singleton | |
this.name = "SingletonTester"; | |
this.pointX = options.pointX || 6; | |
this.pointY = options.pointY || 10; | |
} | |
// our instance holder | |
var instance; | |
// an emulation of static variables and methods | |
var _static = { | |
name: "SingletonTester", | |
// Method for getting an instance. It returns | |
// a singleton instance of a singleton object | |
getInstance: function( options ) { | |
if( instance === undefined ) { | |
instance = new Singleton( options ); | |
} | |
return instance; | |
} | |
}; | |
return _static; | |
})(); | |
var singletonTest = SingletonTester.getInstance({ | |
pointX: 5 | |
}); | |
// Log the output of pointX just to verify it is correct | |
// Outputs: 5 | |
console.log( singletonTest.pointX ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment