Skip to content

Instantly share code, notes, and snippets.

@nfroidure
Created May 30, 2013 07:52
Show Gist options
  • Save nfroidure/5676346 to your computer and use it in GitHub Desktop.
Save nfroidure/5676346 to your computer and use it in GitHub Desktop.
Part of my blog post Revisiting Singleton Design Pattern : http:///www.insertafter.com
// Inherit JavaScript Singleton
function ParentConstructor() {}
ParentConstructor.prototype.publicProperty1=1;
var InheritSingleton=(function(parentConstructor) {
// creating a variable to contain the instance
var instance=null;
// creating singleton constructor
function Constructor() {
// assigning instance to our variable
instance=this;
}
// adding parent object to the singleton constructor prototype
function F() {}
F.prototype = (parentConstructor.getInstance?
parentConstructor.getInstance():
new parentConstructor());
Constructor.prototype=new F();
// here goes public method and properties
Constructor.prototype.publicProperty2=2;
Constructor.prototype.publicMethod2=function() {
console.log('In public method 2.');
_myPrivateFunction();
};
// creating a constructor to generate an exception
var FakeContructor=function() {
throw SyntaxError('Singleton : Use getInstance instead.');
}
// associating him getInstance()
FakeContructor.getInstance=function(){
return instance || new Constructor();
};
return FakeContructor;
})(ParentConstructor);
// Usage
var singleton=InheritSingleton.getInstance();
console.log(singleton.publicProperty1);
// 1
console.log(singleton.publicProperty2);
// 2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment