difference between call bind apply
In JavaScript,
call, apply, and bind are methods used to control the this context within a function and to pass arguments to that function.1.
call()- Execution: Invokes the function immediately.
- Arguments: Takes the
thisvalue as the first argument, followed by arguments for the function passed individually (comma-separated).
const person = {
name: "Alice"
};
function greet(greeting, punctuation) {
console.log(`${greeting}, ${this.name}${punctuation}`);
}
greet.call(person, "Hello", "!"); // Output: Hello, Alice!
2.
apply()- Execution: Invokes the function immediately.
Arguments: Takes the
this value as the first argument, followed by an array (or array-like object) of arguments for the function.const person = {
name: "Bob"
};
function greet(greeting, punctuation) {
console.log(`${greeting}, ${this.name}${punctuation}`);
}
greet.apply(person, ["Hi", "."]); // Output: Hi, Bob.
3.
bind()Does not invoke the function immediately. Instead, it returns a new function with the specified
this context permanently bound.Takes the
this value as the first argument, optionally followed by arguments to be pre-filled (curried) into the new function. These pre-filled arguments will be used when the new function is eventually called.const person = {
name: "Charlie"
};
function greet(greeting, punctuation) {
console.log(`${greeting}, ${this.name}${punctuation}`);
}
const boundGreet = greet.bind(person, "Hey");
boundGreet("?"); // Output: Hey, Charlie?
Summary of Differences:
call and apply execute the function immediately; bind returns a new function to be executed later.call takes arguments individually; apply takes an array of arguments; bind can take initial arguments that are pre-filled into the new function.call and apply return the result of the function execution; bind returns a new function.