I try to sort my thoughts about how javascript\'s bind() works.
I see that if I do
var f = function (a) { ... }
var g = f.bind(obj);
g(1)
You never passed any arguments — you only ever set context. call
's first argument is received as context (this
), and arguments 2 onwards are received as the called function's arguments 1 and onwards. Meanwhile, bind
creates a new function with a new context — arguments are passed when it's invoked.
Here are ways of passing 1
as function f
's argument a
following on from your first code block:
f( 1 );
g( 1 );
g.call( this, 1 );
g.apply( this, [ 1 ] );
Once you bound an object to a function with bind
, you cannot override it. It's clearly written in the specs, as you can see in MDN documentation:
"The bind() function creates a new function (a bound function) with the same function body (internal call property in ECMAScript 5 terms) as the function it is being called on (the bound function's target function) with the this value bound to the first argument of bind(), which cannot be overridden."
That means, also if you do:
g.call(1);
You will get obj
as this
, and not 1
– on the browsers that follows the specs.
You can of course binds multiple arguments, so:
var sum = function(a, b, c) { return a + b + c };
var sumAB = sum.bind(null, 1, 5);
var sumC = sumAB.bind(null, 2);
console.log(sumC());
But the context object will be always the one specified with the first bind
, because it cannot be overwritten.
Just to avoid confusion, the first argument of call is the context object (this
), then you will have the rest of the argument.
It means:
var obj = { foo: function(bar) { console.log(bar) } };
obj.foo('hello');
// equivalent to:
var foo = obj.foo;
foo.call(obj, 'hello');
Hope it helps.