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]))();
Method 1: Using the apply() method: The apply() method is used to call a function with the given arguments as an array or array-like object. It contains two parameters. The this value provides a call to the function and the arguments array contains the array of arguments to be passed.
Creating an Array Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [item1, item2, ...]; It is a common practice to declare arrays with the const keyword.
of() The Array. of() method creates a new Array instance from a variable number of arguments, regardless of number or type of the arguments.
There are two ways to pass arguments to a function: by reference or by value. Modifying an argument that's passed by reference is reflected globally, but modifying an argument that's passed by value is reflected only inside the function.
var wrapper = function(f, args) { return function() { f.apply(this, args); }; }; function Constructor() { this.foo = 4; } var o = new (wrapper(Constructor, [1,2])); alert(o.foo);
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 this
and 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 this
that you apply it to is set with the new keyword. A new this
object 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 .bind
method
var wrapper = function(f, args) { var params = [f].concat(args); return f.bind.apply(f, params); };
See example
with ECMAscript 5 you can:
function createInstanceWithArguments (fConstructor, aArgs) { var foo = Object.create(fConstructor.prototype); fConstructor.apply(foo, aArgs); return foo; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With