I was trying out the code here http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/ for the bind
method
var data = [
{name:"Samantha", age:12},
{name:"Alexis", age:14}
]
var user = {
// local data variable
data :[
{name:"T. Woods", age:37},
{name:"P. Mickelson", age:43}
],
showData:function (event) {
var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1
console.log (this.data[randomNum].name + " " + this.data[randomNum].age);
}
}
// Assign the showData method of the user object to a variable
var showDataVar = user.showData.bind(user);
showDataVar (); // // P. Mickelson 43 (from the local data array)
I understand that the bind method can be used to change what this
refers to inside a function.
However, if I change this line var showDataVar = user.showData.bind(user);
to two lines
var showDataVar = user.showData;
showDataVar.bind(user);
the previous behavior resumes (i.e. the code prints Samantha) as if the second line did not have any effect. Can you please explain how bind
works?