views:

62

answers:

2

I think I need something like ruby's splat * here.

function foo() {
  var result = '';
  for (var i = 0; i < arguments.length; i++) {
    result += arguments[i];
  }
  return result;
}

function bar() {
  return foo(arguments) // this line doesn't work as I expect
}

bar(1, 2, 3);

I want this to return "123", but instead I get "[object Arguments]". Which makes sense, I suppose. It's passing the object that represents the arguments, but not the arguments individually.

So how do I simply forward any number of arguments to another function that takes any number of arguments?

+5  A: 

To correctly pass the arguments to another function, you need to use apply:

function bar() {
  return foo.apply(null, arguments);
}

The apply method takes two parameters, the first is the thisObj, the value of it will be used as the this value inside the invoked function, if you use null or undefined, the this value inside the function will refer to the global object.

The second argument that apply expects, is an array-like object that contains the arguments to be applied to the function.

Check the above example here.

CMS
+1  A: 

Try this return foo.apply(this,arguments). Also you can just use Array.prototype.slice.apply(arguments).join('') for your foo function.

Teja Kantamneni