Understanding bind method

 

In this article we will understand bind method. Bind method used for currying (Currying is like a function returning closure function) functions and setting this value.

What is Currying? https://en.wikipedia.org/wiki/Currying

What is currying in JavaScript http://stackoverflow.com/questions/36314/what-is-currying

So let’s start

bind() method

bind() method allow us to bind specific object to function’s 'this' value. As we discussed above it is used for setting this value explicitly. It also helps you in borrowing methods. The use of bind() function is to create a new function (bound function).

Syntax: fun.bind(thisArg[, arg1[, arg2[, ...]]])

thisArg

The value to be passed as 'this' parameter to the target function when the bound function is called. The value is ignored if the bound function is constructed using the new operator.

arg1, arg2, ...

Arguments to prepend to arguments provided to the bound function when invoking the target function.

Before understanding bind, call and apply you must have better understanding of this keyword in JavaScript. Nice post for understanding 'this' keyword (http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/ ).

 

Setting this Value using bind() method

So in this example we will see how bind method is used in setting this value explicitly.

 

Setting this value explicitly using bind().
<!DOCTYPE html>
<html>
    <head>
      
      <title>bind methods</title>
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
     </script>

    </head>
    <body>
       <div id="divbind" onclick="personInfoOnclick.showDetailsOnClick();" 
       style="height:10px; display:block;"> Show Information </div>
    </body>
	  <script type="text/javascript" src="callapplyandbind.js"></script>
	 
</html>
var personInfoOnclick = {
	info:{
	       firstName:"Deepak",
	       lastName:"Singh",
	       address:"Pune"
	},

       showDetailsOnClick:function(event){
	       console.log(this.info.firstName+" "+this.info.lastName+" "+this.info.address);
	}
};

/**
Here click event is bound to DOM element div and so the context of 'this' 
belongs to the div element and because of that it is not able to find 'info' 
property in 'this' context.
*/
// TypeError: this.info is undefined
$("#divbind").click(personInfoOnclick.showDetailsOnClick); 

/**
So to fix the above issue there are different ways.
*/

//Step 1. Use of bind() method to set the this value explicitly
$("#divbind").click(personInfoOnclick.showDetailsOnClick.bind(personInfoOnclick));
// Step 2. is passing annonymous callback function
$("#divbind").click(function(event) {
	personInfoOnclick.showDetailsOnClick(event);
});
// step 3. call method showDetailsOnClick from DOM element.
//onclick="personInfoOnclick.showDetailsOnClick();"
/*<div id="divbind" onclick="personInfoOnclick.showDetailsOnClick();" 
style="height:10px; display:block;"> Show Information </div>
*/
var info = {
	       firstName:"Rajveer",
	       lastName:"Singh",
	       address:"Pune"
}

var personInfoOnclick = {
	info:{
	       firstName:"Deepak",
	       lastName:"Singh",
	       address:"Pune"
	},

       showDetailsOnClick:function(event){
	       console.log(this.info.firstName+" "+this.info.lastName+" "+this.info.address);
	}
};

var showDetailsOnClickVar = personInfoOnclick.showDetailsOnClick;

showDetailsOnClickVar(); // Rajveer Singh Pune 

// Why it is printing Rajveer Singh why not Deepak Singh?

/**
This is because showDetailsOnClickVar is now a global function and context of this 
keyword belongs to global scope.

If variable 'info' was not defined as a global varaible and then you will try 
to call showDetailsOnClickVar() function as above then you will get JavaScript Error 
TypeError: this.info is undefined, because 'this.info' belongs to 
personInfoOnclick object locally and showDetailsOnClickVar() will try to find 'info' 
property in global 'this' which is undefined.

This can be fixed using bind() method by setting the this value       explicitly 
(i.e. passing personInfoOnclick object explicitly).
*/

var showDetailsOnClickVar = personInfoOnclick.showDetailsOnClick.bind(personInfoOnclick);

showDetailsOnClickVar(); // Deepak Singh Pune 

 

Borrowing with bind()

bind() also used for borrowing methods from other objects. Although it is always better to borrow methods using apply method. 

var personInfoOnclick = {
	info:{
	       firstName:"Deepak",
	       lastName:"Singh",
	       address:"Pune"
	},

       showDetailsOnClick:function(event){
	       console.log(this.info.firstName+" "+this.info.lastName+" "+this.info.address);
	}
};

// How to use the concept of borrow using bind
var dispOtherInfo = {
	info:{
	       firstName:"Jon",
	       lastName:"Smith",
	       address:"Cincinnati"
	}
}

dispOtherInfo.showDetailsOnClick = personInfoOnclick.showDetailsOnClick.bind(dispOtherInfo);
// Jon Smith Cincinnati
dispOtherInfo.showDetailsOnClick(); 

 

Partially applied functions (Currying)

bind() method is used for currying a functions. In brief currying in JavaScript is an ability to apply function partially (i.e. you can pass subset of the argument and get function and then pass rest of the parameter to get the final result when needed).

Let's see the example how bind method can help you in currying functions. 

function suggestActivity(age, temp, name){
	var msg = "";
	if(age < 10)
	       msg = "but in Guardian supervision";

       if(temp>=80){
	       console.log("Hey "+name+", You can Swim "+msg);
	}else if(temp >=60 && temp < 80){
	       console.log("Hey "+name+", You can play game like (Baseball, Tennis etc.) "+msg);
	}else if(temp >=40 && temp < 60){
	       console.log("Hey "+name+", You can Play Cricket or golf "+msg);
	}else if(temp < 40){
	       console.log("Hey "+name+", You can do Skiing "+msg);
	}
}

// first parameter is this, since we are not using 'this' keyword hence passing as a null
suggstActivityforAdlt = suggestActivity.bind(null, 30);

suggstActivityforAdlt(80, "Deepak Singh");
// Now you have to simply change the temprature and name to know the suggested activity.
suggstActivityforAdlt(60, "Jon");
suggstActivityforAdlt(50, "Richard");
suggstActivityforAdlt(38, "Tony");

suggstActivityforKid = suggestActivity.bind(null, 8);

suggstActivityforKid(80, "Dhiraaj");
// Now you have to simply change the temprature and name to know the suggested activity.
suggstActivityforKid(60, "Rajveer");
suggstActivityforKid(50, "Tom");
suggstActivityforKid(38, "Angela");

 

Hope you have got fare understanding of bind() method in JavaScript.

 
Keep Reading and Keep Learning.
 

Reference: MSDN bind() function