Sobes.tech
Middle

Räägi mulle JavaScriptis konteksti säilitamise viisidest: bind, call, apply. Kuidas nad erinevad?

sobes.tech AI

Vastus AI-lt

In JavaScript, functions are first-class objects and have a dynamic call context (this). The methods bind, call, and apply allow managing 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 to be called later;
  • apply is useful when arguments are already in an array;
  • bind is useful for preserving context in callbacks and event handlers.