Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should you pass Math as the first argument to Math.max.apply?

Tags:

javascript

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.

like image 727
Jake Sellers Avatar asked Oct 02 '22 07:10

Jake Sellers


2 Answers

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.

like image 150
lionel Avatar answered Oct 05 '22 12:10

lionel


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.

like image 35
PlasmaPower Avatar answered Oct 05 '22 10:10

PlasmaPower