Jamie Dixon
Jamie Dixon

Reputation: 54001

Accessing arguments collection in bind function

When returning .bind() from a higher order function, is it possible to access the arguments collection within the bound context?

Take the following function as an example:

function reverse(fn) {
     return function ()  { 
        return fn.apply(this, [].slice.call(arguments).reverse()) 
     };
}

Ideally I'd like to remove the inner function wrapper and simply return something like:

return fn.apply.bind(fn, [].slice.call(arguments).reverse());

(Obviously arguments is scoped to the outer function and not the returned function, which is what I'm after).

Is this possible through some mechanism I'm unaware of or is the function wrapper a necessity?

Upvotes: 2

Views: 58

Answers (1)

Alnitak
Alnitak

Reputation: 339927

.bind is a good way of setting the context and/or a fixed initial parameter list when you cannot control the lexical scope of the function you're trying to .bind.

Internally .bind just creates a function anyway, so offers no advantage here - in my experience it has few other uses that an inner function wouldn't achieve better.

In fact in this case it simply can't work - you have to provide some sort of scope for where the .reverse() call happens, and the only place that can be is in that inner function.

Upvotes: 1

Related Questions