I checked out this reference link and ended up using Matthew's solution, as it works for me.
var factory ={};
factory.Tree = function(arg1,arg2,arg3,arg4){
console.log(arg1+""+arg2+""+arg3+""+arg4);
}
function instantiate(classname){
return new (function(a){ return factory[classname].apply(this,a);})(Array.prototype.splice.call(arguments,1));
// also is this ^^^ a good practice? instead of declaring the temp function beforehand
// function t(a) {return factory[classname].apply(this,a);}
// return new t(Array.prototype.splice.call(arguments,1));
}
var newObj = instantiate("Tree",1,2,3,4); // this prints 1234 --> works
Though, I'm not sure why using user123444555621's solution only works if I pass in "arguments" (that is everything including "classname"):
function instantiate(classname){
return new (Function.prototype.bind.apply(factory[classname], arguments));
}
var newObj = instantiate("Tree",1,2,3,4); // this prints 1234 --> works
but if I slice "arguments" and remove "classname", then pass in the result array, it does not work as expected:
function instantiate(classname){
var args = Array.prototype.splice.call(arguments,1);
// ^^ I checked and this prints 1,2,3,4 as well
return new (Function.prototype.bind.apply(factory[classname], args));
}
var newObj = instantiate("Tree",1,2,3,4); // this prints 234undefined
I'm not sure why but somehow it seems like the args array is sliced (again) and removes its first element (1 in this case).
Could someone offer any insights? Thanks