.call() vs .apply() vs .bind()
call, apply, and bind CAN explicitly set what this will be. Normal function call cannot control this.
function greet() {
console.log(this);
}
greet();In browser → this = window
In strict mode → this = undefined
In Node → this = global (or undefined in modules)
You did not choose what this is. JavaScript decided based on call context.
greet.call({ name: "Ram" });
You force JS to use: this = { name: "Ram" }
Difference
• call → Call now • apply → Apply array & call now • bind → Bind & call later
Call
- Calls the function immediately
- Arguments passed one by one
Using call the function runs right at that line of code.
function greet(age) {
console.log(this.name, age);
}
const user = { name: "Ram" };
greet.call(user, 25); // Ram 25
in above example .call(user, 25) means: "Run the function greet, and inside it treat this as user."
Apply
- Calls the function immediately
- Arguments passed as array
greet.apply(user, [25]); // Ram 25
Difference with call is
fn.call(thisArg, a, b, c)
fn.apply(thisArg, [a, b, c])
Bind
- Does NOT call function immediately
- Returns a new function with fixed this
const boundFn = greet.bind(user, 25);
boundFn();Production Example
Example 1
class App {
constructor() {
this.name = "Selvesan";
}
print() {
console.log(this.name);
}
}
const app = new App();
setTimeout(app.print, 1000); // ❌ this becomes undefined
setTimeout(app.print.bind(app), 1000);Example 2
const person1 = {
name: "Hari",
speak() {
console.log("Hello " + this.name);
}
};
const person2 = { name: "Sita" };
person1.speak.call(person2); // Hello Sita