Skip to content

Instantly share code, notes, and snippets.

@sebdeckers
Created October 11, 2012 01:56
Show Gist options
  • Save sebdeckers/3869685 to your computer and use it in GitHub Desktop.
Save sebdeckers/3869685 to your computer and use it in GitHub Desktop.
Singleton in Javascript using a closure and the module pattern
// 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