2

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?

6
  • I can't figure out what you're actually trying to achieve... Commented Jan 20, 2015 at 15:22
  • You can make a partial function of it and return that Commented Jan 20, 2015 at 15:23
  • The removal of the inner function (return function () {...}) Commented Jan 20, 2015 at 15:23
  • sure, but what is the outer function supposed to do? Commented Jan 20, 2015 at 15:24
  • The outer function takes a function, and returns a function that is the same as the one passed in, except the arguments are reversed. So reverse(console.log)("World", "Hello") -> "Hello" "World" Commented Jan 20, 2015 at 15:25

1 Answer 1

1

.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.

Sign up to request clarification or add additional context in comments.

3 Comments

This is just for practice but it would have been more aesthetically pleasing to my pedantic mind if I could have removed the inner function got away with a one liner. Ah well. Onward and up. Cheers for answering Alnitak.
If it's just for the aesthetics of a one liner, you could do this: return Function(["fn"], "fn.apply(fn, [].slice.call(arguments, 1).reverse());").bind(null, fn); but that's just awful for my taste.
@JamieDixon ultimately, you have to arrange for the argument array to be reversed before invoking the desired function, and AFAIK that's simply impossible with a call to .bind. You have to provide some scope in which that reversal takes place, and your inner function provides that.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.