Javascript: When to use function_name.
Many times I see statements like the following
Y.CustomApp.superclass.render.apply(this, arguments);
I know how to apply works. By MDN
Calls a function with the specified value and arguments supplied as an array.
But why not call the method directly?
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()
.
You are using apply
when a function is not a method in an object.
Example:
var obj = { firstName: 'John', lastName: 'Doe' }
function getName() {
return this.firstName + ' ' + this.lastName;
}
var name = getName.apply(obj);