.call() and .apply()
In JavaScript, both call
and apply
are methods used to invoke functions and set the this
context explicitly to an object different from the current context. However, they differ in how they handle function arguments.
The call
Method
The call
method invokes a function with a given this
value and arguments provided individually. This is particularly useful when you know the number of arguments that the function expects. It allows you to invoke a function as if it were a method of a particular object, even if it's not.
Syntax:
For example, if we have a function that adds two numbers and logs the result, we can use call
to invoke it with a specific context:
The apply
Method
The apply
method is similar to call
but instead of taking arguments individually, it takes an array of arguments. This makes apply
very handy when you don't know in advance how many arguments will be passed to the function, or when the arguments are already in an array or array-like object.
Syntax:
Using the same example as above, we can use apply
like this:
Key Differences
- Argument Handling:
call
takes an argument list, whereasapply
takes a single array of arguments. This distinction is crucial when you are working with functions where the number of parameters isn't fixed or they are naturally collected in an array. - Performance: Historically,
call
has generally been slightly faster thanapply
, particularly when dealing with functions that accept a large number of arguments. However, with modern JavaScript engines, this difference is often negligible.
Use Case Example:
If you are implementing a function like Math.max
which does not inherently handle array inputs to find the maximum number, you can elegantly use apply
to pass an array directly: