The JavaScript bind method returns a different function set to a specified context. Explain how this function works and give at least one example of its usage.
When you call the bind method of a function, it creates and return a new version of your function (Known as bound function) with its this context defined to the object you've passed to the first argument of bind.
Example:
var name = "John";
var age = 34;
var peter = {
name: "peter",
age: 14
};
var mary = {
name: "mary",
age: 12
};
function sayNameAge() {
console.log(this.name + " - " + this.age);
}
//Creates a new bound function wrapping
sayNameAge function using peter as 'this.' context.
var sayPeterInfo = sayNameAge.bind(peter);
//Creates a new bound function wrapping
sayNameAge function using mary as 'this.' context.
var sayMaryInfo = sayNameAge.bind(mary);
//Prints "John - 34" because 'this.' will relate to the global window context.
sayNameAge();
sayPeterInfo(); //Prints "peter - 14"
sayMaryInfo(); //Prints "mary - 12"When we define sayNameAge it's this context is related to the window object.
console.log(window.name) will print John because the var name = "John"; was created at the global context.
When we execute the statement var sayPeterInfo = sayNameAge.bind(peter);, we are assigning a bound function returned by the bind method of sayNameAge function to the variable sayPeterInfo with the this context pointed to peter object.
The same happens to var sayMaryInfo = sayNameAge.bind(mary); statement, but pointing the this to mary object.
bind method also provides the option to add additional parameters to the binded function.
As an example let's display the height of Peter and Mary.
//Creates a new bound function wrapping
sayNameAge function using peter as 'this.' context.
// Also adds an additional parameter of 120 which will be interpreted as arguments[0] inside sayNameAge function.
var sayPeterInfoHeight = sayNameAge.bind(peter,120);
//Creates a new bound function wrapping
sayNameAge function using mary as 'this.' context.
// Also adds an additional parameter of 110 which will be interpreted as arguments[0] inside sayNameAge function.
var sayMaryInfoHeight = sayNameAge.bind(mary,110);
sayPeterInfoHeight(); //Prints "peter - 14" and "peter height is: 120cm"
sayMaryInfoHeight(); // Prints "mary - 12" and "mary height is: 110cm"This parameter definition operation when using bind is called currying and adds great flexibility to your programming.
The examples above may look silly for now, but when we start creating elements and events on the fly, function binding will prove itself a clean lightweight way handle your code.
PS:. The live demo of this example is HERE.
Guilherme Soldateli
09/25/2017
Career Path 3: Modern Frontend Developer