Javascript: Forwarding function calls that take variable number of arguments [duplicate]
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?
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.
精彩评论