Junior
What are the differences between the call, bind, and apply functions in JavaScript?
sobes.tech AI
Answer from AI
call and apply invoke a function immediately, setting the this context and passing arguments. call accepts arguments separately, while apply accepts them as an array. bind returns a new function with a bound this context and optional arguments, without invoking the original function.
// Example of using call and apply
const obj = { name: 'Alice' };
function greet(greeting) {
console.log(`${greeting}, ${this.name}!`);
}
greet.call(obj, 'Hello'); // Hello, Alice!
greet.apply(obj, ['Hi']); // Hi, Alice!
// Example of using bind
const boundGreet = greet.bind(obj, 'Hi');
boundGreet(); // Hi, Alice!
| Method | Call | Arguments | Return value |
|---|---|---|---|
call |
Immediate | Listed separately | Function result |
apply |
Immediate | As array | Function result |
bind |
Creates new function | Can pass arguments during bind or call of the returned function | New function with bound context |