Skip to content

Instantly share code, notes, and snippets.

@naoisegolden
Created August 6, 2014 13:54
Show Gist options
  • Save naoisegolden/42cd1fd248d399f2923b to your computer and use it in GitHub Desktop.
Save naoisegolden/42cd1fd248d399f2923b to your computer and use it in GitHub Desktop.
var mySingleton = (function () {
// Instance stores a reference to the Singleton
var instance;
function init() {
// Singleton
// Private methods and variables
function privateMethod(){
console.log( "I am private" );
}
var privateVariable = "Im also private";
return {
// Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
},
publicProperty: "I am also public",
};
};
return {
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
// Usage:
// somewhere in the code
var singleA = mySingleton.getInstance();
singleA.publicMethod();
// somewhere else in the code
var singleB = mySingleton.getInstance();
singleB.publicMethod();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment