What is bind in JavaScript and when to use

The bind() method creates a new function that, when called, has its own this keyword set to the provided value.

There are two types of binding:

1. Binding an object

2.Binding a parameter

Binding an Object:

Instead of writing a new function from scratch, the bind() method can be used to create a modified copy of a function.

The first argument for the bind() method is required.

It is the object with which we want to bind our new copy of the function.

Below is an example of object binding:

class Person t{

constructor(name, age){

this.name = name;

this.age = age;

}

}

Person.prototype.printName = function ( ){

console. log( this.name +’ ‘+ this.age);

}

var katy = new Person( “Katy”, 25);

var printKaty = Person. prototype.printName.bind( katy);

printkaty();

Binding a parameter:

If there is a need to specify the arguments passed to a function, we can pass those fixed values in bind() after the first argument.

Below is an example of parameter binding:

function multiply(a, b){

return a * b;

}

var double = multiply.bind( this, 2);

console. log( double(3));

Leave a Reply

Your email address will not be published. Required fields are marked *