Sobes.tech
Junior — Middle

Could you explain the difference between call, apply, and bind methods in JavaScript and how they are used to control the call context of a function?

sobes.tech AI

Answer from AI

In JavaScript, the methods call, apply, and bind are used to control the context (this) when invoking a function:

  • call(thisArg, arg1, arg2, ...) — calls the function immediately, setting this to thisArg and passing arguments separately.

  • apply(thisArg, [argsArray]) — similar to call, but arguments are passed as an array.

  • bind(thisArg, arg1, arg2, ...) — does not call the function immediately but returns a new function with the this context bound to thisArg and optionally preset arguments.

Example:

function greet(greeting, punctuation) {
  console.log(greeting + ', ' + this.name + punctuation);
}

const person = { name: 'Ivan' };

greet.call(person, 'Hello', '!'); // Hello, Ivan!
greet.apply(person, ['Greetings', '...']); // Greetings, Ivan...

const greetIvan = greet.bind(person, 'Hello');
greetIvan('!!!'); // Hello, Ivan!!!

Thus, these methods allow explicitly setting the object that this refers to inside the function.

Could you explain the difference between call, apply… - sobes.tech