Sobes.tech
Middle

What are the differences between call, apply, and bind?

sobes.tech AI

Answer from AI

call, apply and bind are methods for managing the this context in JavaScript.

  • call invokes a function with a specified context and arguments passed separately.
function greet(greeting) {
  console.log(greeting + ', ' + this.name);
}
const person = { name: 'Ivan' };
greet.call(person, 'Hello'); // Hello, Ivan
  • apply is similar to call, but arguments are passed as an array.
greet.apply(person, ['Good morning']); // Good morning, Ivan
  • bind does not invoke the function immediately but returns a new function with a bound context and optionally, arguments.
const greetPerson = greet.bind(person, 'Good afternoon');
greetPerson(); // Good afternoon, Ivan

Thus, call and apply invoke the function immediately, while bind creates a new function with a fixed context for later invocation.

What are the differences between call, apply, and… - sobes.tech