Skip to content

Instantly share code, notes, and snippets.

@carldanley
Last active December 21, 2015 11:29
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 carldanley/6ac14bb0766e8bd146c5 to your computer and use it in GitHub Desktop.
Save carldanley/6ac14bb0766e8bd146c5 to your computer and use it in GitHub Desktop.
Example of the Singleton pattern
var mySingleton = ( function( window, undefined ) {
var instance = null;
// revealing module pattern that handles initialization of our new module
function initializeNewModule() {
function myMethod() {
alert( 'my method' );
}
function myOtherMethod() {
alert( 'my other method' );
}
return {
someMethod : myMethod,
someOtherMethod : myOtherMethod
};
}
// handles the prevention of additional instantiations
function getInstance() {
if( ! instance ) {
instance = new initializeNewModule();
}
return instance;
}
return {
getInstance : getInstance
};
} )( window );
// example usage
mySingleton.getInstance().someMethod(); // alerts "my method"
mySingleton.getInstance().someOtherMethod(); // alerts "my other method"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment