Understanding function.bind
Function binding in JavaScript can be confusing.
Say we have two dirty dogs, Titus and Kevin. We have also declared a brush function that cleans their fur and then console.logs different messages depending on whether the dog is happy or not.
var TitusThePitbull = {name: 'Titus', fur: 'dirty', brush: brush};
var KevinTheMaltese = {name: 'Kevin', fur: 'dirty', brush: brush};function brush(isHappy){
this.fur = 'clean';
if (isHappy) {
console.log( this.name + ' is clean and happy!' );
} else {
console.log( this.name + ' is clean but glares at you' );
}
}TitusThePitbull.brush(true); // 'Titus is clean and happy!'
KevinTheMaltese.brush(); // 'Kevin is clean but glares at you'
Pay attention to the this keyword inside the bark function. At calltime, this gets bound to the nearest object that invoked the function containing this.
For the first brush call, this refers to TitusThePitbull.
For the second brush call, this refers to KevinTheMaltese.
Currently, this brush works for both Kevin and Titus. But what if using the same brush is not sanitary? Say you want to have two different brushes for both of them and so you give Titus a new brush.
var titusBrush = brush.bind(TitusThePitbull);Enter function.bind
What this line of code does is essentially take the brush function, makes a new copy of this brush and then “slaps on” Titus’ name tag onto it. This brush will now only brush Titus. Try calling:
titusBrush(); // 'Titus is clean and happy!'
titusBrush(false); // 'Titus is clean but glares at you'You’ll notice that this is now Titus’ exclusive brush.
Get EK’s stories in your inbox
Join Medium for free to get updates from this writer.
Let’s now walk through a simpler implementation for Function.bind
var titusBrush = brush.bind(TitusThePitbull);
///////////////////////////////////////////////////////////////////Function.prototype.bind = function(context){ //Get a reference to the function you wish to bind
var funcYouWantToBind = this; //Return a brand new function that retains a reference to the
//above funcYouWantToBind and context variables
return function(){ return funcYouWantToBind.apply(context, arguments); };}
What fun.apply does here in this case is it takes funcYouWantToBind’s this keyword, sets it to context and then passes the arguments variable to this modified version of funcYouWantToBind.
Why use function.bind?
In some cases you might want to specify the this keyword explicitly to avoid problems. For example, when using setTimeout/setInterval.
Other times you might want to actually preset some values every time you invoke the function. For example if you used:
var titusAmazingBrush = brush.bind(TitusThePitbull, true);This new brush will always make Titus happy. It will never make him unhappy even if you call:
titusAmazingBrush(false);
