I’m trying to write a function
that would use its first argument, then send the rest (not known how many) to another one:
function consume_data() {
args = consume_data.arguments;
do_some(args[0]);
consume_the_rest(args[1], args[2], args[3] ... );
}
Do I have to use strings to compose the call and eval or is there a neater way?
The traditional JavaScript way… unfortunately.
You should use the
argumentsvariable that’s provided in the local variable scope. Then borrow.slice()fromArray.prototypeto get an Array of arguments starting with the second.Then use the
.apply()method to pass those arguments as a collection, which will be destructured into individual arguments in theconsome_the_restmethod.Why?
The reason you need to borrow
Array.prototype.sliceis that anargumentsobject is not really an Array, so it doesn’t have the prototyped Array methods.The first argument given to
.apply()sets the calling context (thisvalue) of the function you’re calling, and as I mentioned above, theargsArray will be destructured into individual arguments in the execution context of the function you’re calling. This is what make it possible to pass an unknown number of arguments.An alternative, with caveats.
If you don’t care about the calling context of the function, you can actually do this instead…
Here the
.call()method is just like.apply()except that you pass arguments individually instead of as a collection. So we’re calling.call()using.apply(), which will set theconsume_the_restas the calling context of.call(), and spread theargumentsout, setting the first argument as the calling context arg of.call(), and the rest the normal arguments to be passed on.It will be as though you did…
…so the first argument will actually be used as the calling context, and the rest will be the ones you expect.
Again, only do this if you don’t care about the calling context of the function you’re calling.