The problem is that I need to create a new instance of the passed class
Is there a way to rewrite this function, so it could accept any number of arguments?
function createInstance(ofClass, arg1, arg2, arg3, ..., argN){
return new ofClass(arg1, arg2, arg3, ..., argN);
}
This function should create an instance of the passed class. Example:
var SomeClass = function(arg1, arg2, arg3){
this.someAttr = arg3;
.....
}
SomeClass.prototype.method = function(){}
var instance = createInstance(SomeClass, 'arg1', 'arg2', 'arg3');
So this should be true.
instance instanceof SomeClass == true
Right now, I’ve just limited N to 25, with hope that more arguments are rarely used.
The other answers are on the right track, but none of them mention that you have to be aware of the fact that
argumentsis not anArray. It’s a special structure that behaves like anArray.So before you use it like an
Array, you can convert it to one like this:Sorry, I just copied the code with
constructoretc. and didn’t think about what it would actually do. I’ve updated it now to what you want. You’ll find that it’s calling the constructor withoutnew, so you won’t get the same behavior. However, John Resig (author of jQuery) wrote on this very issue.So based on John Resig’s article you’ve got two ways to solve it. The more elaborate solution will be the most transparent to the user, but it’s up to you which solution you choose.
Here is a “perfect” solution if you only intend to support browsers that have the
Object.createfunction (which is a pretty big percentage now compared to three years ago):The resulting objects from both
new cls(x)andcreateInstance(cls, x)should be identical.