Javascript: When to use function_name.
The reasons you are using apply()
are one or two of the following:
- You already have arguments that will be passed to the function as an array or an array-like object;
- You want to
this
bind in a certain way when you call the function.
If you have a list of values in an array for some reason and you know those values are exactly what you need to pass to the function, what else would you do? Something like:
if (array.length == 1)
theFunction(array[0]);
else if (array.length == 2)
theFunction(array[0], array[1]);
else ...
clearly scary.
If you know you want to this
be tied to some object, you can always make the function a temporary property of the object and call the function through the object, but that's also pretty awful. If all you have to do is bind this
and the arguments are not in the array, well, your alternative is to use .call()
instead .apply()
.
source to share