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



Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s