0

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?

Ankit
  • 6,772
  • 11
  • 48
  • 84

1 Answers1

1

bind does not modify a function, it returns a new function. Thus, showDataVar.bind(user) does nothing, unless you preserve the result and use it.

As to how bind works, it is roughly equal to this:

Function.prototype.fakeBind = function(obj) {
  var that = this;
  return function() {
    return that.apply(obj, arguments);
  }
};
Amadan
  • 191,408
  • 23
  • 240
  • 301
  • thanks. for the first part I read the documentation and my brain just did not process that bind is returning a new function :P – Ankit Jul 09 '15 at 03:57