What’s the difference between these two functions?
function bind_1(f, o) {
if (f.bind)
return f.bind(o);
else
return function() { return f.apply(o. arguments); };
}
function bind_2(f, o) {
if (f.bind)
return f.bind(o);
else
return f.apply(o. arguments);
}
Vadim and Corbin are both mostly correct, but to add a little specificity and verbosity (I speak big words), bind_1 returns a function that will always call the given function (f) with the given arguments (o) set as the context – setting the context means that inside the function the this keyword will refer to the assigned context object. Whereas bind_2 will return either: the function (f) with the context (o), or return the result of calling the function (f) with the context (o).
Function.prototype.bind can also be used for partial function application. For instance, if you don’t care to use the context inside a function you can provide functions with arguments already applied and therefore simplify subsequent calls:
The first argument passed to .apply(), .call(), or .bind() is changing the context of the function/method. The context is the value of the this keyword; thus, inside of the function the this value will be whatever is passed as the first argument. Here I was using null because in this case the function doesn’t need a specific value for the context; and null is fewer characters than undefined, and feels better than some garbage value (“” – empty string, {} – empty object, etc.). So the remaining two variables are assigned as the first set of arguments to the function.