Created
May 2, 2018 13:16
-
-
Save matteodanelli/995a2ce00e3fab7403f1207547a7803a to your computer and use it in GitHub Desktop.
JS Singleton
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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