In Lua, a function like this would be valid:
function FuncCallHack(Func, ...)
return Func(...)
end
Is there a way I could do this in JavaScript? ...
means "all unindexed parameters in the form of an ungrouped array" to those unfamiliar with Lua. I have tried ...
in JavaScript, and it appeared to be nonfunctional, and as Google doesn't like searching for special characters, it's not much help.
JavaScript has the arguments
pseudo-array and the apply
function; you can do that like this:
function FuncCallHack(Func) {
return Func.apply(this, [].slice.call(arguments, 1));
}
here's how that works:
arguments
- This is a pseudo-array containing all of the arguments passed to the function by the calling code (including the format argument Func
).
[].slice.call(arguments, 1)
is a way to get an array of all of the arguments except the first one. (It's a common idiom. It works by applying the Array#slice
method to the arguments
pseudo-array, using Function#call
[which is a lot like Function#apply
below, it just accepts the args to pass on differently].) Sadly, arguments
itself doesn't necessarily have a slice
method because it's not really an array.
Then we use the Function#apply
method (all JavaScript functions have it) to call Func
using the same this
value that was used for the call to FuncCallHack
, and passing on all of the arguments except Func
to it.
You could also define it slightly differently:
function FuncCallHack(Func, args) {
return Func.apply(this, args);
}
...which is still really easy to use:
FuncCallHack(SomeFunction, [1, 2, 3]);
// Note this is an array --^-------^