Problem Statement
Explain call, apply, and bind methods in detail. When would you use each? Provide examples.
Explanation
Call, apply, and bind are methods for controlling the this value in function calls. They are essential for managing context in JavaScript.
Call method:
Invokes a function with specified this value and individual arguments. First parameter is this, rest are function arguments. Executes immediately. Use when you know arguments individually.
Apply method:
Invokes a function with specified this value and array of arguments. First parameter is this, second is array. Executes immediately. Use when you have arguments in an array.
Bind method:
Creates a new function with permanently bound this value. Returns new function, does not execute immediately. Can pre-set arguments for partial application. Use for event handlers, callbacks, or creating specialized functions.
Key differences:
Call and apply execute immediately, bind returns new function. Call takes comma-separated arguments, apply takes array. Bind permanently fixes this, call and apply use it for single invocation.
When to use call:
Function borrowing. Constructor chaining in inheritance. When you have individual arguments.
When to use apply:
When arguments are in an array. Using array methods on array-like objects. Math methods with array of numbers.
When to use bind:
Event handlers that need specific this. Callbacks that must maintain context. Partial application. Creating reusable specialized functions. React class component methods.
Common use cases:
Borrowing array methods for arguments or NodeList. Maintaining this in setTimeout or event handlers. Constructor chaining. Converting array-like to array. Function composition and currying.
All three methods are fundamental to JavaScript and appear frequently in interviews.
Code Solution
SolutionRead Only