Skip to content

Instantly share code, notes, and snippets.

@Kcko
Forked from mateuszwrobel/singleton.js
Last active February 28, 2020 22:47
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 Kcko/4945195a6aa4aa057f002973529a1862 to your computer and use it in GitHub Desktop.
Save Kcko/4945195a6aa4aa057f002973529a1862 to your computer and use it in GitHub Desktop.
JS: patterns Singleton
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;
}
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment