Skip to content

Instantly share code, notes, and snippets.

@jayeshcp
Created May 3, 2016 21:33
Show Gist options
  • Save jayeshcp/bb184fbca0a626e68689bc9ada4666dd to your computer and use it in GitHub Desktop.
Save jayeshcp/bb184fbca0a626e68689bc9ada4666dd to your computer and use it in GitHub Desktop.
Javascript: Singleton Pattern
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";
var privateRandomNumber = Math.random();
return {
// Public methods and variables
publicMethod: function () {
console.log( "The public can see me!" );
},
publicProperty: "I am also public",
getRandomNumber: function() {
return privateRandomNumber;
}
};
};
return {
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function () {
if ( !instance ) {
instance = init();
}
return instance;
}
};
})();
// Usage:
var singleA = mySingleton.getInstance();
console.log( singleA.getRandomNumber() );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment