We use the Bind() method to call a function with the this value, this keyword refers to the same object which is currently selected . In other words, bind() method allows us to easily set which object will be bound by the this keyword when a function or method is invoked.
The need for bind usually occurs, when we use the this keyword in a method and we call that method from a receiver object, then sometimes this is not bound to the object that we expect to be bound to. This results in errors in our program.
Now, a simple program to print the name which is called by this keyword when the function printFunc() is invoked.
Here is no problem to access the name “ABC”, this keyword bind the name variable to the function. It is known as default binding. this keyword refers geeks object.
Now see the below code,
//no output is produced by this code//
Here we made a new variable function printFunc2 which refers to the function printFunc() of object geeks. Here the binding of this is lost, so no output is produced.
To make sure that any binding of this is not to be lost, we are using Bind() method.
By using bind() method we can set the context of this to a particular object. So we can use other variables also to call binded function.
Use bind() method in the previous example:
The bind() method creates a new function where this keyword refers to the parameter in the parenthesis in the above case geeks. This way the bind() method enables calling a function with a specified this value.
In this example there is 3 objects, and each time we call each object by using bind()method.
ABC contributes about C++ CDE contributes about JAVA IJK contributes about C#