1

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.

1
  • You'll want to see call and apply; in particular, apply applies here. Commented Oct 29, 2013 at 18:09

4 Answers 4

3

You are looking for Function.apply()

f.apply(window, args); // pass something other than null to set 'this' within the call
Sign up to request clarification or add additional context in comments.

2 Comments

note that you can't use apply() if you use "new ", you'll have to manually fill-in the parameters until ES6 is widely supported.
@dandavis: Or var o = Object.create(f.prototype); f.apply(o, args);
1

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.

Comments

1

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.

Comments

-1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.