The bind()
function in JavaScript is used to make a function more specific in its usage. There are two types of ‘binding’:
A function declared in a class can be called through any instance of that class; but, what if we want a function which can perform only the task of one instance of that class and can be called without using that instance? For this scenario, instead of writing a new function from scratch, we use the bind()
method to create a modified copy of that function. The first argument for the bind()
method is necessary, and it is the object with which we want to bind our new copy of the function. The keyword this
, everywhere in the copy, will now refer to this bound object.
Suppose there is a class, Person
, with the method printName()
. To print information for “Katy”, without writing a completely new function, we require a function printKaty()
. Now, we are able to pass the object Katy
(type: Person
) to the bind()
method which will return our required function:
class Person{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();
If there is need to specify the arguments passed to a function, we can pass those fixed values in bind()
after the first argument. Now, this new function will be called by passing the unbound arguments normally; these unbound arguments will first be appended to the bound arguments, and then the original function will be called.
Let us say multiply(a, b)
multiplies two numbers. We can ‘bind’ parameter a
to 2 so that it always returns b
multiplied by 2. This gives us a new function, double(x)
, without having to write it.
Note: Pass
this
as the first argument when binding a function which is NOT part of a class.
function multiply(a, b){return a * b;}var double = multiply.bind(this, 2);console.log(double(3));