Call a function with 'arguments' as separate arguments
I'm trying to pass the arguments
variable of a function as separate arguments to another function. I tried this:
functio开发者_运维知识库n call_function(func) {
func(arguments);
}
However, call_function(someFunction, 123, 456)
actually calls someFunction([someFunction, 123, 456])
. Regardless of the function itself being passed, it is passed as an Arguments
object/array-like thing, but I'd rather call the function in this case as someFunction(123, 456)
.
What I also tried is: func(Array.prototype.slice.call(arguments, 1))
to remove the function (first argument), but obviously this actually returns an array, i.e. it passes the array as the first argument to the function.
How could I code call_function
so that a call like call_function(someFunction, 123, 456)
results in someFunction(123, 456)
being called?
You can use the apply
function to call a function with the array as arguments.
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply
精彩评论