Trusted answers to developer questions

What is the JavaScript bind?

Free System Design Interview Course

Many candidates are rejected or down-leveled due to poor performance in their System Design Interview. Stand out in System Design Interviews and get hired in 2024 with this popular free course.

The bind() function in JavaScript is used to make a function more specific in its usage. There are two types of ‘binding’:


1. Binding an object

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.

Example

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:

Binding an object
Binding an object
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();

2. Binding a parameter

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.

Example

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.

Binding a parameter
Binding a parameter
function multiply(a, b){
return a * b;
}
var double = multiply.bind(this, 2);
console.log(double(3));

RELATED TAGS

javascript
bind
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?