Skip to content

Instantly share code, notes, and snippets.

@FGRibreau
Created February 8, 2015 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FGRibreau/1f89ba04d4d3ab7e3e1b to your computer and use it in GitHub Desktop.
Save FGRibreau/1f89ba04d4d3ab7e3e1b to your computer and use it in GitHub Desktop.
Addy Osmani - Essential JavaScript Design Patterns - Singleton issue
//This "SingletonTester" is not a valid Singleton because:
var InnerConstructor = SingletonTester.getInstance({
pointX: 5
}).constructor;
console.log(new InnerConstructor() !== new InnerConstructor()); // true
// 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