I have written the following function that permits creation of singleton classes from given classes:
function SingletonFrom(Constructor) {
return function() {
var self = arguments.callee;
if (self._instance === undefined) {
switch (arguments.length) { // this is ugly
case 0: self._instance = new Constructor(); break;
case 1: self._instance = new Constructor(arguments[0]); break;
case 2: self._instance = new Constructor(arguments[0], arguments[1]); break;
// [...]
case 10: // ...
default: throw new Error('Error in Singleton: Constructor may take at most 10 arguments'); break;
}
}
return self._instance;
}
}
Example:
var Array_Singleton = new SingletonFrom(Array);
var x = new Array_Singleton(1,2,3); // [1,2,3]
var y = new Array_Singleton(0,0,0,0); // [1,2,3]
alert(x === y); // true
It works great, however I'm not quite happy with the switch
statement. The problem is passing a variable number of arguments to a constructor called with the "new
" keyword is not possible. So, my Constructor function must not take more than 10 arguments. For example, this will fail:
new Array_Singleton(1,2,3,4,5,6,7,8,9,10,11);
Any way to work around this?