Skip to content

Instantly share code, notes, and snippets.

@henryspivey
Forked from prof3ssorSt3v3/6-singleton.js
Last active October 30, 2019 20:41
Show Gist options
  • Save henryspivey/0949dda3f156d69c24116795cec4888b to your computer and use it in GitHub Desktop.
Save henryspivey/0949dda3f156d69c24116795cec4888b to your computer and use it in GitHub Desktop.
/**
* Create an example of a JavaScript Singleton.
* After the first object is created, it will return additional
* references to itself
*/
let obj = (function () {
let objInstance; //private variable
function create() { //private function to create methods and properties
let _isRunning = false;
let start = function() {
_isRunning = true;
}
let stop = function() {
_isRunning = false;
}
let currentState = function() {
return _isRunning;
}
return {
start:start,
stop: stop,
currentState: currentState
}
}
return {
getInstance: function() {
if(!objInstance) {
objInstance = create();
}
return objInstance;
}
};
})();
// obj here is the same for both instances
let obj1 = obj.getInstance();
let obj2 = obj.getInstance();
console.log(obj1.currentState())
console.log(obj2.currentState())
obj1.start()
console.log(obj1.currentState())
console.log(obj2.currentState())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment