6

Can someone explain this function?

var bindbind = Function.prototype.bind.bind(Function.prototype.bind);

I understand the result it produce:

var bindedContextFunc = bindbind(function)(context);
bindedContextFunc(args);

But do not understand process of creating this functions, I mean part bind(Function.prototype.bind)

4
  • "context" would be better as "thisValue" or similar. Commented Nov 22, 2012 at 2:23
  • @RobG: What's wrong with "context"? I see it used often and I think it is more descriptive than the technical term. Do you have a link for me (us) to read? Commented Nov 22, 2012 at 3:01
  • In ECMAScript, "context" is used in regard to execution context, which includes all the parameters and scope of the currently executing code. It includes a this value and is controlled by how the code is written. It is static. In contrast, a function's this value is dynamic and set completely by how the function is called, it has nothing to do with how the function is declared or intialised. So calling "this" context is inappropriate. Those who do so need to read and understand the specification for the language they are using. Commented Nov 22, 2012 at 9:37
  • @RobG interesting information, thanks. However on a higher level (without knowing behaviour details) this looks exactly like "context". Commented Nov 22, 2012 at 10:25

1 Answer 1

4

OK. We have three times the Function.prototype.bind function here, whose (simplified) code

function bind(context) {
    var fn = this;
    return function() {
        return fn.apply(context, arguments);
    }
}

I will abbreviate in a more functional style with lots of partial application: bindfn(context) -> fncontext.

So what does it do? You have got bind.call(bind, bind) or bindbind(bind). Let's expand this to bindbind. What if we now supplied some arguments to it?

bindbind(bind) (fn) (context)

bindbind(fn) (context)

bindfn(context)

fncontext

Here we are. We can assign this to some variables to make the result clearer:

bindbind = bindbind(bind)

bindfn = bindbindanything(fn) // bindfn

contextbindfn = bindfnanything(context) // fncontext

result = contextbindfnanything(args) // fncontext(args)

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

2 Comments

could you elaborate why this solution is better (or probably I should ask why does it exist) if we can just do fn.bind(context)(args) to achieve same result?
Assuming you have an api which wants to return the bindfn - it does not know the context yet. Then you could either use Function.prototype.bind.bind(fn) - which is lengthy - or just bindbind(fn). Not sure whether there's a real-world application, though.

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.