Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of how to implement a Singleton pattern in JavaScript.
/*
* The instance symbol should be defined in the scope
* in which you want the singleton to exist. This does
* not necessarily mean globally. Just within your
* execution context.
*/
let instance
const Singleton = (() => {
const createInstance = () => {
console.log('Calling createInstance')
return true
}
return {
getInstance: () => {
console.log('Call getInstance');
if (instance === undefined) {
instance = createInstance()
}
return instance
},
}
})()
Singleton.getInstance()
Singleton.getInstance()
Singleton.getInstance()
Singleton.getInstance()
// Output
// Calling createInstance
// Call getInstance
// Call getInstance
// Call getInstance
// Call getInstance
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment