Table of Contents

Introduction

JavaScript bind() method creates a new function with a specified this value and, optionally, some arguments already provided. Unlike call() and apply(), it does not execute the original function immediately. Instead, it returns a reusable function that can be called later. This makes bind() useful when passing methods as callbacks, preserving an object’s context, and creating functions with preset arguments.

JavaScript bind() Method Syntax

The bind() method is available on functions through Function.prototype. Its syntax is:

const boundFunction = functionName.bind(thisArg, arg1, arg2, ...);
  • thisArg: The value that will be used as this when the new function is called.
  • arg1, arg2, ...: Optional arguments to preset for the new function. Any arguments supplied later are added after these preset arguments.

The original function is not executed when bind() is called. The method returns a new function whose this value is bound to the supplied context.

How the bind() Method Works

In JavaScript, the value of this in a regular function depends on how that function is called. If you extract a method from an object and call it separately, it may no longer refer to the original object. The bind() method solves this by creating a function that remembers the chosen context.

const user = {
  name: "Ayesha",
  showName: function() {
    console.log(this.name);
  }
};

const showUserName = user.showName.bind(user);

showUserName(); // Ayesha

Here, bind(user) returns a new function. When showUserName() is called, this inside showName() refers to the user object, even though the function is called through a separate variable.

Setting this with bind()

The first argument passed to bind() determines the this value for calls to the returned function. You can use the same function with different objects by creating separate bound functions.

function introduce() {
  return `My name is ${this.name}.`;
}

const employee = { name: "Rahim" };
const customer = { name: "Nadia" };

const introduceEmployee = introduce.bind(employee);
const introduceCustomer = introduce.bind(customer);

console.log(introduceEmployee()); // My name is Rahim.
console.log(introduceCustomer()); // My name is Nadia.

Both returned functions use the same original introduce() function, but each one has a different fixed context.

Passing Arguments with bind()

The bind() method can preset arguments as well as the this value. These preset arguments are sometimes called partially applied arguments. When the returned function is called, any new arguments are placed after the arguments supplied to bind().

function calculateTotal(price, quantity, discount) {
  return price * quantity - discount;
}

const calculateForThreeItems = calculateTotal.bind(null, 500, 3);

console.log(calculateForThreeItems(100)); // 1400

In this example, 500 and 3 are preset as the first and second arguments. The value 100, supplied when the bound function is called, becomes the third argument.

Using bind() to Create Reusable Functions

Bound functions are useful when the same operation needs to run repeatedly with a consistent context or a fixed set of parameters. Instead of repeatedly passing the same values, create the bound function once and reuse it.

function greet(greeting, punctuation) {
  console.log(`${greeting}, ${this.name}${punctuation}`);
}

const member = { name: "Sadia" };

const sayHello = greet.bind(member, "Hello");

sayHello("!"); // Hello, Sadia!
sayHello("."); // Hello, Sadia.

The greeting and context are fixed when sayHello is created. The punctuation can vary each time it is called.

Using bind() with Event Listeners

One common use of bind() is preserving the context of an object method when it is used as an event handler. When a method is passed directly to an event listener, the value of this inside the handler may not be the object that originally contained the method.

const buttonController = {
  message: "Button clicked",

  handleClick: function() {
    console.log(this.message);
  }
};

const button = document.querySelector("#myButton");

button.addEventListener(
  "click",
  buttonController.handleClick.bind(buttonController)
);

The bound callback ensures that this inside handleClick() refers to buttonController. Without binding, the handler’s context would follow the event-listener calling rules rather than automatically remaining the controller object.

In an application, keep a reference to the bound function if you later need to remove the event listener. Calling bind() again creates another function, so this will not remove the original listener:

const handleClick = buttonController.handleClick.bind(buttonController);

button.addEventListener("click", handleClick);

// Later:
button.removeEventListener("click", handleClick);

Using bind() with setTimeout()

When an object method is passed to setTimeout(), it is called later by the timer mechanism. The method may lose its expected object context. You can use bind() to preserve that context.

const notification = {
  message: "Your task is complete",

  show: function() {
    console.log(this.message);
  }
};

setTimeout(notification.show.bind(notification), 1000);

After one second, the bound function runs and logs the message from the notification object. The same approach can be used with callback-based APIs that invoke a supplied function later.

bind() and Partial Function Application

Partial function application means creating a function by fixing some of the arguments of another function. The bind() method supports this pattern by allowing you to provide arguments after the thisArg parameter.

function formatMessage(prefix, name, suffix) {
  return `${prefix} ${name}${suffix}`;
}

const createWelcomeMessage = formatMessage.bind(null, "Welcome");

console.log(createWelcomeMessage("Karim", "!"));
// Welcome Karim!

console.log(createWelcomeMessage("Mina", "."));
// Welcome Mina.

The first parameter is fixed as "Welcome", while the name and suffix are provided later. Since the function does not use this, null is used for the context.

bind() with Objects and Method Borrowing

You can use bind() to create a function that borrows a method from one object while permanently using another object as its context. This is helpful when a method contains reusable behavior but should operate on a different data object.

const person = {
  getFullName: function(separator) {
    return this.firstName + separator + this.lastName;
  }
};

const account = {
  firstName: "Nusrat",
  lastName: "Jahan"
};

const getAccountName = person.getFullName.bind(account, " ");

console.log(getAccountName()); // Nusrat Jahan

The method is defined on person, but the bound function uses account as its context. The separator is also preset to a space.

Difference Between call(), apply(), and bind()

The call(), apply(), and bind() methods all provide ways to control the this value of a regular function. Their main difference is how and when the target function executes and how arguments are supplied.

Method Arguments Execution Returns
call() Passed individually. Executes immediately. The original function’s result.
apply() Passed as an array or array-like object. Executes immediately. The original function’s result.
bind() Can preset arguments individually. Executes when the returned function is called. A new bound function.

The following example demonstrates the difference:

function describe(greeting, punctuation) {
  return `${greeting}, ${this.name}${punctuation}`;
}

const user = { name: "Ayesha" };

console.log(describe.call(user, "Hello", "!"));
// Hello, Ayesha!

console.log(describe.apply(user, ["Hello", "!"]));
// Hello, Ayesha!

const boundDescribe = describe.bind(user, "Hello");

console.log(boundDescribe("!"));
// Hello, Ayesha!

Use call() when you want to execute a function immediately with separate arguments. Use apply() when the arguments are already in an array-like collection. Use bind() when you need a new function that can be called later with a fixed context.

What Happens When bind() Is Used More Than Once?

A bound function keeps the this value established by its first bind() call. Binding that already-bound function again does not replace its original context. However, additional arguments can still be preset.

function showName(prefix) {
  return prefix + this.name;
}

const firstUser = { name: "Rahim" };
const secondUser = { name: "Nadia" };

const firstBound = showName.bind(firstUser);
const secondBound = firstBound.bind(secondUser, "User: ");

console.log(secondBound()); // User: Rahim

The second call to bind() does not change this to secondUser. The original bound context remains firstUser, while the new prefix argument is applied.

bind() and Arrow Functions

Arrow functions do not have their own this value. Instead, they capture this from the surrounding lexical scope. As a result, using bind() on an arrow function cannot change its this value.

const user = {
  name: "Mina",

  showName: () => {
    console.log(this.name);
  }
};

const anotherUser = { name: "Karim" };

const boundArrow = user.showName.bind(anotherUser);

boundArrow(); // Does not use anotherUser as this

For methods that need a dynamically assigned this value, use a regular function. Arrow functions are useful when lexical this is the intended behavior, such as callbacks nested inside a method.

bind() and Constructor Functions

Bound functions can also be used with the new operator when the original function is constructible. When a bound function is called as a constructor, the newly created object becomes this; the thisArg supplied to bind() is ignored. Arguments preset by bind() are still applied.

function Product(name, price) {
  this.name = name;
  this.price = price;
}

const createBook = Product.bind(null, "JavaScript Guide");

const book = new createBook(450);

console.log(book.name);  // JavaScript Guide
console.log(book.price); // 450

Here, the product name is preset, and the price is supplied when the constructor is called. The new operator creates the object and assigns it as this.

Understanding the Return Value of bind()

Unlike call() and apply(), bind() returns a function rather than the result of executing the original function. You can store this returned function in a variable, pass it to another function, or invoke it whenever needed.

function add(a, b) {
  return a + b;
}

const addTen = add.bind(null, 10);

console.log(typeof addTen); // function
console.log(addTen(5));     // 15

The call to bind() creates addTen with the first argument preset to 10. The function returns 15 only when addTen(5) is executed.

Using bind() in Modern JavaScript

Modern JavaScript offers several alternatives for managing function context and arguments, including arrow functions, closures, and class fields. However, bind() remains valuable when a callback must retain a particular object context or when a reusable function needs preset parameters.

For example, a class can bind a method once in its constructor so that callbacks consistently refer to the class instance:

class Counter {
  constructor() {
    this.count = 0;
    this.increment = this.increment.bind(this);
  }

  increment() {
    this.count++;
    console.log(this.count);
  }
}

const counter = new Counter();
const updateCounter = counter.increment;

updateCounter(); // 1
updateCounter(); // 2

Without binding, extracting counter.increment into another variable would lose the instance context when called as a plain function. Binding it in the constructor keeps this connected to the correct instance.