Javascript – Bind

http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/

We use the Bind () method primarily to call a function with the this value set explicitly. It other words, bind () allows us to easily set which specific object will be bound to this when a function or method is invoked.

Bind is used to bind a specific this to the function. For example:

// This data variable is a global variable​
var data = [
  {name: "A", age: 20},
  {name: "B", age: 15}
]

var user = {
  data : [
    {name: "A", age: 25},
    {name: "B", age: 40}
  ],
  showData:function(event) {
    //var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1
    var randomNum = 1
    console.log (this.data[randomNum].name + " " + this.data[randomNum].age);

  }
}

////
var showDataVar = user.showData;
showDataVar(); /// This will show name B and age 15. Because the this inside is the outside this not the inside one

var showDataVar = user.showData.bind(user);
showDataVar(); /// This will show name B and age 40. This is because you bound the user as this so the this will use the data array inside inside of the outside one



Leave a comment