apply-1 Bind () Allows us to Borrow Methods
Bind () Allows us to Borrow Methods http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/
by shenoyvnm
JavaScript
var user = {
data: [{
name: "Rahul",
age: "20"
}, {
name: "Santosh",
age: "23"
}],
showData: function () {
var randomNum = ((Math.random() * 2 | 0) + 1) - 1; // random number between 0 and 1
console.log(this.data[randomNum].name + " " + this.data[randomNum].age);
}
}
var cars = {
data: [{
name: "Honda Accord",
age: 14
}, {
name: "Tesla Model S",
age: 2
}]
}
// We can borrow the showData () method from the user object we defined in the last example.
// Here we bind the user.showData method to the cars object we just created.
/* below debugger is important to understand how is "bind" different from apply/call. The site javascript is sexy says abt a problem
"One problem with this example is that we are adding a new method (showData) on the cars object and we might not want to do that just to borrow a method because the cars object might already have a property or method name showData. We don’t want to overwrite it accidentally. "
To better understand the problem, see debugger below
and see what this has to say. Again see this("Local"scope in dev tools) after " cars.showData = user.showData.bind (cars)" is executed. You will see showData method is given to the this object.
*/
debugger;
cars.showData = user.showData.bind(cars);
cars.showData(); // Honda Accord 14