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)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Nik
  • 9,063
  • 7
  • 66
  • 81
  • "context" would be better as "thisValue" or similar. – RobG Nov 22 '12 at 02: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? – Bergi Nov 22 '12 at 03:01
  • In ECMAScript, "context" is used in regard to [execution context](http://ecma-international.org/ecma-262/5.1/#sec-10), 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. – RobG Nov 22 '12 at 09:37
  • @RobG interesting information, thanks. However on a higher level (without knowing behaviour details) `this` looks exactly like "context". – Nik Nov 22 '12 at 10:25

1 Answers1

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)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 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? – Nik Nov 22 '12 at 16:13
  • 1
    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. – Bergi Nov 22 '12 at 16:20