Advance JavaScript (DOM, BOM, Web API) / Object Oriented Programming

call, apply, bind

In JavaScript, the value of this depends on how a function is called, not where it is written.

Sometimes we want to:

  • manually control this

  • borrow a function from another object

  • permanently fix the value of this for later use

That’s where call, apply, and bind help.


✅ call()

What it does

Calls a function immediately with a specific this value and arguments passed individually.

Syntax

func.call(thisArg, arg1, arg2, ...)

✅ Example

const person = { name: "Bhaskar" };

function greet(city, country) {
  console.log(`Hi, I'm ${this.name} from ${city}, ${country}`);
}

greet.call(person, "Kolkata", "India");

✅ apply()

What it does

Works like call, but arguments are passed as an array.

Syntax

func.apply(thisArg, [arg1, arg2, ...])

Example

greet.apply(person, ["Kolkata", "India"]);

When useful

  • When arguments are already in an array

  • Example: Math.max

console.log(Math.max.apply(null, [10, 3, 99])); // 99

✅ bind()

What it does

Returns a new function with this permanently bound.

⚠️ It does NOT call the function immediately.

Syntax

const newFn = func.bind(thisArg, arg1, arg2, ...);

Example

const sayHi = greet.bind(person, "Kolkata", "India");

sayHi(); // runs later

Use cases

  • Fix this inside callbacks

  • React event handlers (common!)

  • Delayed function execution


🧠 Whats happening behind the scene

const person = { name: "Bhaskar" };

function greet(city, country) {
  console.log(`Hi, I'm ${this.name} from ${city}, ${country}`);
}

greet.call(person, "Kolkata", "India");

greet.call(person, "Kolkata", "India")

✔️ It calls the greet function

✔️ It sets this inside greet to person

✔️ It passes the arguments "Kolkata" and "India"

So inside the function, JavaScript treats it as:

this.name  →  person.name  → "Bhaskar"
city       → "Kolkata"
country    → "India"

And it behaves like you wrote:

console.log("Hi, I'm Bhaskar from Kolkata, India");

Same for apply() and bind()


🔥 Comparison Table

Feature

call()

apply()

bind()

Executes immediately

✅ Yes

✅ Yes

❌ No

How arguments are passed

individually

array

individually (optional)

Returns

function result

function result

new function

Use case

quick manual call

when args in array

save for later


⚠️ Common Mistakes

✅ bind does not call the function

greet.bind(person); // nothing happens yet

✅ apply requires array-like, not individual values

greet.apply(person, "Kolkata", "India"); // ❌ error

✅ Arrow functions ignore call/apply/bind

const arrow = () => console.log(this);
arrow.call({ a: 10 }); // still global `this`