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)