I'm going through John Resig's JavaScript ninja tutorial and on #51 I see this:
// Find the largest number in that array of arguments
var largestAllButFirst = Math.max.apply( Math, allButFirst );
allButFirst
is just a small array of integers. I believe I understand what apply
does, but I can't understand why Math
is being passed as an argument to apply
.
The first parameter of the .apply
is the context. Inside the function body the this
keyword will reference that value.
Example:
function sum(a){ return this + a; }
sum.apply(1, [1]); // will return 2
// or with .call
sum.call(1, 1); // also returns 2
By default if you call Math.max
the context (the this
keyword) is automatically set to Math
. To keep this behavior Math
is passed as the first parameter in apply.
Passing it Math
is not necessary, anything will work here. Math
indicates the context of the operation, however max
does not require a context. This means that Math.max.apply(undefined, allButFirst)
will also work. See this answer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With