call(), apply(), and bind() are methods that allow you to change the this context in JavaScript.
🔹 Differences & Examples
1️⃣ call()
- Calls a function immediately with a specified
thisvalue. - Arguments are passed individually.
function greet(language) { console.log(`${this.name} speaks ${language}`); } const person = { name: "Hemant" }; greet.call(person, "JavaScript"); // Output: Hemant speaks JavaScript 2️⃣ apply()
- Works like
call(), but arguments are passed as an array.
greet.apply(person, ["ReactJS"]); // Output: Hemant speaks ReactJS 3️⃣ bind()
- Does NOT call the function immediately.
- Returns a new function with the
thisvalue fixed.
const greetPerson = greet.bind(person); greetPerson("TypeScript"); // Output: Hemant speaks TypeScript 📌 Summary
| Method | Calls Function Immediately? | Arguments |
|---|---|---|
call() | ✅ Yes | Passed individually |
apply() | ✅ Yes | Passed as an array |
bind() | ❌ No (Returns new function) | Passed individually |
✅ Use call() when passing individual arguments.
✅ Use apply() when passing an array of arguments.
✅ Use bind() when you need a reusable function with a fixed this.
Top comments (0)