HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Function Bind

With the bind() method, an object can borrow a method from another object. Unlike call() and apply(), which invoke the function immediately, bind() creates a new function that can be executed later.


Method Borrowing with Bind

Here, the person object has a method, and we use bind() to create a new function that is permanently linked to member.

const person = {
  firstName: "Mim",
  lastName: "Akter",
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}

const member = {
  firstName: "Redo",
  lastName: "Hub"
}

let fullName = person.fullName.bind(member);
console.log(fullName()); // "Redo Hub"

Preserving 'this'

The most common use case for bind() is when you want a function to keep its this value, even if it is passed as a callback.

When a method is passed as a callback (e.g., in a setTimeout), the context is lost. this becomes the global object or undefined.

const person = {
  firstName: "Mim",
  sayHi: function () {
    console.log("Hi " + this.firstName);
  }
}

// Without bind, "this" is lost after 1 second
setTimeout(person.sayHi, 1000); // Output: "Hi undefined"

// With bind, "this" is preserved
let boundHi = person.sayHi.bind(person);
setTimeout(boundHi, 1000); // Output: "Hi Mim"

Key Points to Remember

  • bind() creates a new function (it doesn't execute it immediately)
  • It is used to permanently link the this context to a specific object
  • Critical for callbacks, event listeners, and asynchronous code
  • Different from call() and apply() which run the function right away
  • Arrow functions often replace the need for bind() because they inherit this from their parent scope