I know the possibility to call a function with an array of arguments with apply(obj,args);
Is there a way to use this feature when creating a new instance of a function?
I mean something like this:
function A(arg1,arg2){
var a = arg1;
var b = arg2;
}
var a = new A.apply([1,2]); //create new instance using an array of arguments
I hope you understand what i mean… ^^^
Thanks for your help!
Solved!
I got the right answer. To make the answer fit to my question:
function A(arg1,arg2) {
var a = arg1;
var b = arg2;
}
var a = new (A.bind.apply(A,[A,1,2]))();
We take a function and arguments and create a function that applies the arguments to that function with the this scope.
Then if you call it with the new keyword it passes in a new fresh
thisand returns it.The important thing is the brackets
new (wrapper(Constructor, [1,2]))Calls the new keyword on the function returned from the wrapper, where as
new wrapper(Constructor, [1,2])Calls the new keyword on the wrapper function.
The reason it needs to be wrapped is so that
thisthat you apply it to is set with the new keyword. A newthisobject needs to be created and passed into a function which means that you must call.apply(this, array)inside a function.Live example
Alternatively you could use ES5
.bindmethodSee example