just as you can with any other object. Some defaults that come along with being a function are
apply(). We’re going to tkae a closer look at two similar, but slightly different methods:
- both methods invoke the function caller, using a context passed in as the first parameter
thiscontext, and the arguments are passed with commas
thiscontext, and the arguments are passed as an Array
Why use either?
apply are ways to re-use some functionality.
They provide us a way to borrow functions, so we can avoid code duplication.
With either method, you can execute the function with a modified
When a function is called normally, it’s
this value is set normally (either the containing
object or the global object).
Choosing one over the other
call is a good choice when the arguments for a function are known.
apply is a good choice when the function has an unknown amount of arguments.
You can deconstruct the arguments yourself, and do whatever is necessary.
arguments gives us access to all parameters passed in, specified or not.
robert.greeting method does not take any parameters, but we’re still able to call it with a variable amount of parameters.
It’s important to also note that that although
arguments has a
length method, it is not an Array.
Using this knowledge, we can be clever about our usage of
Math.max(), for example.
Math.max() takes arguments as comma separated values, and returns the max value.
If we gave it an array, we’d get
NaN, because an Array can’t be converted into a number for the function.
Instead, we can use
apply in this form:
Here, we don’t need to invoke
Math.max with any specific
We just want to call the method using an array.
apply(), we can do just that, and avoid writing our own version of
max() for arrays.