Skip to content

Instantly share code, notes, and snippets.

@matteodanelli
Created May 2, 2018 13:16
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 matteodanelli/995a2ce00e3fab7403f1207547a7803a to your computer and use it in GitHub Desktop.
Save matteodanelli/995a2ce00e3fab7403f1207547a7803a to your computer and use it in GitHub Desktop.
JS Singleton
var mySingleton = (function() {
var instance;
function init() {
// Private methods and variables
function privateMethod() {
console.log("I am private");
}
var privateAsync = new Promise(function(resolve, reject) {
// async call which returns an object
// resolve or reject based on result of async call here
});
return {
// Public methods and variables
publicMethod: function() {
console.log("The public can see me!");
},
publicProperty: "I am also public",
getPrivateValue: function() {
return privateAsync;
}
};
};
return {
// Get the Singleton instance if one exists
// or create one if it doesn't
getInstance: function() {
if (!instance) {
instance = init();
}
return instance;
}
};
})();
var foo = mySingleton.getInstance().getPrivateValue().then(function(result) {
// woohoo
}).catch(function(err) {
// epic fail
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment