Javascript binding is done using the Bind() method. With the help of the bind method, we can make one common function and bind different objects, so that the function gives different results when its need. otherwise, it gives the same result or gives an error while the code is executing.

In short, when a function or method is invoked, the bind() method allows us to easily set which object will be bound by this keyword.

var info= {

name : "XYZ",
printFunc: function(){
document.write(this.name);} // XYZ
}
info.printFunc();

In the above example, there is no problem accessing the name, this keyword bind the name variable to the function. This is called as default binding.

This keyword will here point to object i.e info object.

var info = {

name : "XYZ",
printFunc: function(){
    document.write(this);// window object or undefined(strict mode).
    document.write(this.name);
  }
}
var printFunc2= info.printFunc;
printFunc2();

In the above example, we are storing a reference of info.printFunc to printFunc2 variable. After that, we are calling it without an object reference, so this will now refer to the window (global) object or undefined (in strict mode). Hence, the binding of this is lost, so no output is produced.

So basically, the Bind() method is used so that binding of this is not lost.

By using bind() method we can set the context of _this or in simple terms we can bind this _to a particular object.


How to use bind?

  1. The bind() method creates a new function, when invoked, has the this sets to the provided value. See example below:-
var car1 = {
  name : "swift",
  color: "red",
}
var car2 = {
  name : "alto",
  color: "blue",
}
function infoFunc() {
   document.write(this.name + " " + this.color + "<br/>");
 }
infoFunc.bind(car1)(); // swift red
infoFunc.bind(car2)(); // alto blue

There is one common function infoFunc() which is invoked 2times with different objects so that different results are produced. This first binds to car1 object and then to car2 object.

2. Function borrowing which means the bind() allows an object to borrow a method from another object without making a copy of that method.

#this-keyword #binding #javascript #front-end-development #call-apply-bind

Binding Concept in Javascript
1.55 GEEK