these three (call, apply, and bind) are JavaScript function methods that let you explicitly set the value of this when calling a function. The main difference is how arguments are passed and when the function is executed.
πΉ 1. call()
- Executes the function immediately.
- Arguments are passed individually (comma-separated).
function greet(greeting, punctuation) {
console.log(greeting + " " + this.name + punctuation);
}
const person = { name: "Himanshu" };
greet.call(person, "Hello", "!");
// Output: Hello Himanshu!
πΉ 2. apply()
- Executes the function immediately.
- Arguments are passed as an array (or array-like object).
greet.apply(person, ["Hi", "!!"]);
// Output: Hi Himanshu!!
πΉ 3. bind()
- Does NOT execute the function immediately.
- Returns a new function with
thisbound and arguments pre-set (if any). - You call the returned function later.
const boundGreet = greet.bind(person, "Hey");
boundGreet("?");
// Output: Hey Himanshu?
β Key Differences
| Method | Executes Immediately? | How Arguments Are Passed | Returns |
|---|---|---|---|
call | β Yes | Individually (comma-separated) | Result of the function |
apply | β Yes | As an array | Result of the function |
bind | β No | Individually (when binding) | A new function with this bound |
π Quick analogy:
call= “Call me now with these arguments.”apply= “Apply this array of arguments and call me now.”bind= “Bind me to this object and arguments, but donβt call yet β save me for later.”
