Open In App

JavaScript Function binding

In JavaScript function binding happens using the Bind() method. With this method, we can bind an object to a common function, so that the function gives different results when needed. otherwise, it gives the same result or gives an error while the code is executing. We use the Bind() method to call a function with ‘this’ value.

What is ‘this’?

‘this’ refers to the object it belongs to. The exact value of ‘this’ depends on how a function is called. In a method, ‘this’ represents the object that the method was called on, while in a regular function, it typically refers to the global object (in the case of browser environments, it’s the ‘window’ object).



Example 1: In this example, this keyword binds the name variable to the function. It is known as default binding. this keyword refers to geeks object.




let geeks = {
    name: "ABC",
    printFunc: function () {
        console.log(this.name);
    }
}
 
geeks.printFunc();

Output

ABC

Example 2: In this example, the binding of this is lost, so no output is produced.




let geeks = {
    name: "ABC",
    printFunc: function () {
        console.log(this.name);
    }
}
 
let printFunc2 = geeks.printFunc;
printFunc2();

Output
undefined

Example 3: In this example, we are using the bind() method in the previous example. The bind() method creates a new function where this keyword refers to the parameter in the parenthesis. This way the bind() method enables calling a function with a specified this value. 




let geeks = {
    name: "ABC",
    printFunc: function () {
        console.log(this.name);
    }
}
 
let printFunc2 = geeks.printFunc.bind(geeks);
//using bind()
// bind() takes the object "geeks" as parameter//
printFunc2();

Output
ABC

Example 4: In this example, there are 3 objects, and each time we call each object by using the bind()method. 




//object geeks1
let geeks1 = {
    name: "ABC",
    article: "C++"
}
//object geeks2
let geeks2 = {
    name: "CDE",
    article: "JAVA"
}
 
//object geeks3
let geeks3 = {
    name: "IJK",
    article: "C#"
}
 
function printVal() {
    console.log(this.name + " contributes about " +
                this.article + "<br>");
}
 
let printFunc2 = printVal.bind(geeks1);
//using bind()
// bind() takes the object "geeks1" as parameter//
printFunc2();
 
let printFunc3 = printVal.bind(geeks2);
printFunc3();
 
let printFunc4 = printVal.bind(geeks3);
printFunc4();
//uniquely defines each objects

Output
ABC contributes about C++<br>
CDE contributes about JAVA<br>
IJK contributes about C#<br>

Article Tags :