Sobes.tech
Middle

Tell me about ways to preserve context in JavaScript: bind, call, apply. How do they differ?

sobes.tech AI

Answer from AI

In JavaScript, functions are first-class objects and have a dynamic invocation context (this). The methods bind, call, and apply allow you to control this context:

  • call — invokes the function immediately, passing the context and arguments separately.

    func.call(context, arg1, arg2);
    
  • apply — similar to call, but arguments are passed as an array.

    func.apply(context, [arg1, arg2]);
    
  • bind — does not invoke the function immediately but returns a new function with the bound context and, optionally, partially applied arguments.

    const boundFunc = func.bind(context, arg1);
    boundFunc(arg2);
    

Differences:

  • call and apply invoke the function immediately;
  • bind returns a new function for later invocation;
  • apply is convenient when arguments are already in an array;
  • bind is useful for preserving context in callbacks and event handlers.
Tell me about ways to preserve context in JavaScript… - sobes.tech