Reputation: 19915
Let's say we have a function
f = function(a, b, c){
// do something important
}
and an array containing the arguments
var args = [5, 'string', 12] // just any values
Obviously, I could call my function like this :
f(args[0], args[1], args[2])
This is really not elegant, and I look for a better way to accomplish this. Thanks for your suggestions.
Upvotes: 1
Views: 66
Reputation: 596
It depends of your needs (of course)
if elements are homogenous
var sum = function(numbers) {
// do some calculations
}
var randomees = [5, 6, 12]
var total = sum(randomees);
If they are not, they should have some kind of description. I.e. if you are defining options or parameters, then you would consider this
var parameters = {
size:13,
shipped:true,
description:"Laptop"
}
var displayLaptop = function(characteristics) {
console.log(characteristics.size)
}
(or even play with some jQuery.extend ish method)
Upvotes: -1
Reputation: 95528
Use .apply()
. The second argument lets you specify an array of arguments to the function you are trying to call. The first argument is the value of this
you want in the context of the function.
So in your case it would be:
f.apply(null, args);
or
f.apply(window, args);
If you want this
within the context of f
to be the window
object.
Upvotes: 1
Reputation: 2975
Use .apply()
.
f.apply(window, args);
This will work with any array-like object in the second argument position.
It invokes the function f
, and sets the first argument you pass as its this
value (here I just used window
), and distributes the members of the second argument as individual arguments to the function.
The result is as though you had done this:
f(5, 'string', 12);
There's a counterpart to the Function.prototype.apply
method called .call()
. The .call()
method is exactly the same, except that you pass the arguments individually.
f.call(window, 5, 'string, 12);
The purpose of this is the call the function like normal, but set the this
value manually.
Upvotes: 1
Reputation: 3773
You are looking for Function.apply()
f.apply(window, args); // pass something other than null to set 'this' within the call
Upvotes: 3