Skip to content

Instantly share code, notes, and snippets.

@ajayg415
Last active May 26, 2020 07:37
Show Gist options
  • Save ajayg415/666bc74066824c6fc277dac7f9a26509 to your computer and use it in GitHub Desktop.
Save ajayg415/666bc74066824c6fc277dac7f9a26509 to your computer and use it in GitHub Desktop.
Js Singleton Design Pattern
var mySingleton = (function () {
var instance;
function init() {
// 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;
}
};
})();
let st = new mySingleton();
st.getInstance();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment