Functions are objects in JavaScript, functions have methods, including the powerful Apply, Call, and Bind methods. Apply and Call are nearly identical and are frequently used in JavaScript for borrowing methods and for setting the this value explicitly. Apply and Call are ECMAScript3 but Bind is available in ECMAScript5
Bind() and borrow methods
We use bind when we use the this keyword in a method and we call that method from a receiver object; in such cases, sometimes this is not bound to the object that we expect it to be bound to, resulting in errors in our applications.
var car = {
make: "Honda",
model: "Accord",
getCarType: function(){
//this is referring to object car
var type = this.make + " " + this.model;
return type;
},
onButtonClicked: function(event){
var carType = "Car Type = " + this.getCarType();
alert(carType);
}
}
$('#typeButton').click(car.onButtonClicked);
Okay, so what will happen is that clicking on the typeButton will yield an error. Basically, the Jquery typeButton is its own object and you are trying to invoke car.onButtonClicked function on a Jquery button object which has no context of car. It’s like trying to tell Joe to play volleyball but Jeff is the one that plays volleyball. So, now you see the problem, how should we fix it?
$('#typeButton').click(car.onButtonClicked.bind(car));
In JavaScript, we can pass functions around, return them, borrow them, and the like. And the bind () method makes it super easy to borrow methods.