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.
javascript
let geeks = {
name: "ABC" ,
printFunc: function () {
console.log( this .name);
}
}
geeks.printFunc();
|
Example 2: In this example, the binding of this is lost, so no output is produced.
javascript
let geeks = {
name: "ABC" ,
printFunc: function () {
console.log( this .name);
}
}
let printFunc2 = geeks.printFunc;
printFunc2();
|
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.
javascript
let geeks = {
name: "ABC" ,
printFunc: function () {
console.log( this .name);
}
}
let printFunc2 = geeks.printFunc.bind(geeks);
printFunc2();
|
Example 4: In this example, there are 3 objects, and each time we call each object by using the bind()method.
javascript
let geeks1 = {
name: "ABC" ,
article: "C++"
}
let geeks2 = {
name: "CDE" ,
article: "JAVA"
}
let geeks3 = {
name: "IJK" ,
article: "C#"
}
function printVal() {
console.log( this .name + " contributes about " +
this .article + "<br>" );
}
let printFunc2 = printVal.bind(geeks1);
printFunc2();
let printFunc3 = printVal.bind(geeks2);
printFunc3();
let printFunc4 = printVal.bind(geeks3);
printFunc4();
|
Output
ABC contributes about C++<br>
CDE contributes about JAVA<br>
IJK contributes about C#<br>
Last Updated :
03 Jan, 2024
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...