Reputation: 2439
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
.
Upvotes: 6
Views: 304
Reputation: 872
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.
Upvotes: 3
Reputation: 67316
From Mozilla docs:
fun.apply(thisArg, [argsArray])
thisArg: The value of this provided for the call to fun. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode code, null and undefined will be replaced with the global object, and primitive values will be boxed.
So, in your example, Math
is being used as the context for the function (if the keyword this
is used inside).
If no thisArg
is used, then the default is the global object. So, it is good practice to give some context if possible.
Upvotes: 0
Reputation: 1878
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.
Upvotes: 1