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

Unlike call() and apply(), bind() does not immediately invoke the function.

1.Syntax

const boundFunction = functionName.bind(thisArg, arg1, arg2, ...);
  • functionName → the original function
  • thisArg → value to bind as this inside the function
  • arg1, arg2… → optional arguments to preset (partial application)

2.Basic Example

const user = { name: "Zaman" };

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

const boundGreet = greet.bind(user);

boundGreet("Hello"); // Hello, my name is Zaman

this inside boundGreet is now user object
✔ Original greet function remains unchanged

3.Using bind() With Multiple Arguments

function introduce(age, city) {
console.log(`${this.name} is ${age} years old from ${city}`);
}
const user = { name: "Ahmed" };
const boundIntroduce = introduce.bind(user, 30);
boundIntroduce("Dhaka");
// Ahmed is 30 years old from Dhaka

✔ Arguments can be preset (partial application)

 4.Event Handling

const user = { name: "Zaman" };

function greet() {
console.log(`Hello ${this.name}`);
}

// Without bind → `this` points to button
document.querySelector("button").addEventListener("click", greet.bind(user));
// Click → Hello Zaman

✔ Ensures this points to user object inside event handler

5.Partial Application With bind()

function multiply(a, b) {
return a * b;
}
const double = multiply.bind(null, 2); // preset first argument 
console.log(double(5)); // 10 
console.log(double(10)); // 20

✔ Very useful for currying / functional programming

6.Using bind() With Constructor Functions

function Person(name) {
this.name = name;
}
const Zaman = new Person("Zaman");
const showName = function() { 
console.log(this.name); 
}; 
const boundShowName = showName.bind(Zaman); 
boundShowName(); // Zaman 

✔ Can bind any context, including objects created via constructor

Categorized in:

Javascript,