Javascript: Forwarding function calls that take variable number of arguments
UPDATE: Since ES6, you can use the spread syntax to call a function, applying the elements of an iterable object as argument values of the function call:
function bar() {
return foo(...arguments);
}
Note that you can also receive a variable number of arguments as a real array, instead of using the arguments
object.
For example:
function sum(...args) { // args is an array
return args.reduce((total, num) => total + num)
}
function bar(...args) {
return sum(...args) // this just forwards the call spreading the argument values
}
console.log(bar(1, 2, 3)); // 6
In the days of ES3/ES5, to correctly pass the arguments to another function, you needed 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, in non-strict mode, otherwise is undefined
.
The second argument that apply
expects is an array-like object that contains the argument values to be applied to the function.
Check the above example here.
Try this return foo.apply(this,arguments)
. Also you can just use Array.prototype.slice.apply(arguments).join('')
for your foo function.