Skip to content

Instantly share code, notes, and snippets.

@iconifyit
Last active August 25, 2021 02:10
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 iconifyit/a502aeba9facf393a3951edaf53f0c6b to your computer and use it in GitHub Desktop.
Save iconifyit/a502aeba9facf393a3951edaf53f0c6b to your computer and use it in GitHub Desktop.
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