-
-
Save henryspivey/0949dda3f156d69c24116795cec4888b to your computer and use it in GitHub Desktop.
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
/** | |
* 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