apply and call in JS
Function.call and Function.apply are two very important methods and you should be very familiar with them if you are good at functional javascript. The most important and the only purpose of these two methods is to convert one input to another.
These two methods are easy to use but also easy to confuse, people always forget which one they should use… I hope I can help you remember these two methods clearly through this post.
Definition
Here I copy and paste the official definition of two methods from MDN:
call
The call() method calls a function with a given this value and arguments provided individually.
Note: While the syntax of this function is almost identical to that of apply(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.
Syntax:
fun.call(thisArg[, arg1[, arg2[, …]]])
apply
The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).
Note: While the syntax of this function is almost identical to that of call(), the fundamental difference is that call() accepts an argument list, while apply() accepts a single array of arguments.
Syntax:
fun.apply(thisArg, [argsArray])
Test and Clarify
Before I do the test, I hope you all remember the first thing: call accept multiple params, and apply accept an array. You can remember this by remember the A for apply and array. Easier ? :)
Here I wrote a simple test script to clarify two methods. The basic idea is to define a two different functions giveMeArray (accept an array as input) and giveMeParams (accept multiple params as input).
And then I try to run both methods with call and apply:
1 | var giveMeArray = function(arr){ |
Now everything seems pretty clear, right ?
Conclusion
- apply: pass the arr(the second params in apply) to origin function as multiple params
- call: pass all params except the first one to origin function as multiple params
That’s all!