Created
October 11, 2012 01:56
-
-
Save sebdeckers/3869685 to your computer and use it in GitHub Desktop.
Singleton in Javascript using a closure and the module pattern
This file contains 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
// Singleton | |
var immortal = (function () { | |
var therecanbeonlyone = {name: ''}; | |
return function () { | |
return therecanbeonlyone; | |
}; | |
})(); | |
console.log('First there were none', new immortal()); | |
var badguy = new immortal(); | |
badguy.name = 'Duncan MacLeod of the clan MacLeod'; | |
console.log('Then the scotsman reigned', new immortal()); | |
var hero = new immortal(); | |
hero.name = 'Sebastiaan'; | |
console.log('Until a new hero arose', new immortal()); | |
console.log('There can be only one!', badguy === hero); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment