Skip to content

Instantly share code, notes, and snippets.

@sidonath
Created June 6, 2009 07:52
Show Gist options
  • Select an option

  • Save sidonath/124766 to your computer and use it in GitHub Desktop.

Select an option

Save sidonath/124766 to your computer and use it in GitHub Desktop.
Another take on singleton pattern in JavaScript
function singleton(self, wrapper, ctor) {
// support for early failing
if (self instanceof wrapper) {
throw wrapper.name + " " +
"is a singleton, you cannot create its instance. " +
"To get the isntance: " + wrapper.name + "();";
}
if (!ctor) {
return;
}
if (!wrapper.instance) {
wrapper.instance = new ctor();
}
return wrapper.instance;
}
function Hello() {
// fail early if called with new Hello() <- not mandatory
singleton(this, Hello);
function HelloCtor() {
this.id = String(Math.random()).replace("0.", '');
this.hi = function() { alert("Hello, World! " + this.id); };
alert("Constructing: " + this.id);
}
// construct the instance or return constructed
return singleton(this, Hello, HelloCtor);
}
// constructor should be called only once and id should be the same
Hello().hi();
Hello().hi();
// exception should be raised for new Hello()
var caught = false;
try {
(new Hello()).hi();
} catch (ex) {
alert("Exception caught: " + ex);
caught = true;
}
if (!caught) {
alert("Exception not caught when creating singleton")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment