JavaScript
Call Apply Bind
The methods
call,apply, andbindare used for manual management of the context (this) of a function. They are available to all functions through theFunction.prototypeprototype.
call()
- Calls the function immediately, passing
thisand arguments separated by commas. - Used when you need to call a function with a specific context right now.
func.call(thisArg, arg1, arg2, ...);apply()
- Similar to
call(), but arguments are passed in the form of an array or pseudo-array. - Convenient when arguments are already in an array (for example, when using
Math.max).
func.apply(thisArg, [arg1, arg2, ...]);bind()
- Does not call the function immediately, but returns a new function with a fixed
thisand (optionally) partially set arguments. - Used for deferred call or permanent context binding, for example, in event handlers.
const newFunc = func.bind(thisArg, arg1, arg2, ...);Key Ideas
callandapply— execute the function immediately, with different ways of passing arguments.bind— does not execute immediately, but returns a new function.- All three methods allow explicit management of the execution context (
this). - Typical case: loss of context when passing a method as a callback.