I’m a huge fan of ES5’s Function.prototype.bind and currying arguments (basically creating default arguments for functions).
I was fooling around with that a bit, but I can’t for the life of me figure out my own construct anymore. This is my playground:
function hello( arg1, arg2 ) {
console.log('hello()');
console.log('"this" is: ', this);
console.log('arguments: ', arguments);
}
var foo = Function.prototype.call.bind( hello,{what: 'dafuq'}, 2 );
foo( 42 );
The log output for this is as follows:
hello()
"this" is: Object{ what="dafuq" }
arguments: [2,42]
But I don’t understand how on earth the {what: 'dafuq'} object makes its way as a reference for the this within foo. As far as I understand it, we are creating a bound call to Function.prototype.call. Lets check the MDN synopsis for .bind() quickly:
fun.bind(thisArg[, arg1[, arg2[, ...]]])
so, thisArg for .call is the hello function, followed by the arguments list. Basically what happens is this
Function.prototype.call.call( hello, {what: 'dafuq'}, 2);
…uuhhh now my brain hurts a little. I think I have an idea now what happens, but please someone find nice solid words to explain it in detail.
- how
{what: 'dafuq'}becomes thethis reference
It’s because
foois effectively thecallmethod with thehellofunction bound as the calling context, and that object bound as the first argument. The first argument of.callsets the calling context of its calling context. Since you’ve bound it, it means that object always be the calling context.Put it this way…
You’ve bound the calling context of
.calltohello.This is effectively the same as doing…
You’ve also bound the first argument of
.callto{what: "dafuq"}, so this is effectively the same as doing…And finally, you’ve bound the second argument of
.callto2, so this is effectively the same as doing…