Why would you pass 'null' to 'apply' or 'call'?
When there is no value you wish to specify for the this
pointer inside the function and the function you're calling is not expecting a particular this
value in order to function properly.
Wouldn't explicitly passing the keyword this be clearer? Or at least
more human readable. Then again at this point I may not understand why
you would use null.
In your specific case, probably the best thing to pass is the Math
object:
function getMax(arr){
return Math.max.apply(Math, arr);
}
While it turns out that it doesn't matter what you pass as the first argument for Math.max.apply(...)
(only because of the implementation specifics of Math.max()
), passing Math
sets the this
pointer to the exact same thing that it would be set to when calling it normally like Math.max(1,2,3)
so that is the safest option since you are best simulating a normal call to Math.max()
.
Why would you pass 'null' to 'apply' or 'call'?
Here are some more details... When using .call()
or .apply()
, null
can be passed when you have no specific value that you want to set the this
pointer to and you know that the function you are calling is not expecting this
to have any specific value (e.g. it does not use this
in its implementation).
Note: Using null
with .apply()
or .call()
is only usually done with functions that are methods for namespace reasons only, not for object-oriented reasons. In other words, the function max()
is a method on the Math
object only because of namespacing reasons, not because the Math
object has instance data that the method .max()
needs to access.
If you were doing it this way:
function foo() {
this.multiplier = 1;
}
foo.prototype.setMultiplier = function(val) {
this.multiplier = val;
}
foo.prototype.weightNumbers = function() {
var sum = 0;
for (var i = 0; i < arguments.length; i++) {
sum += (arguments[i] * this.multiplier);
}
return sum / arguments.length;
}
var x = new foo();
x.setMultiplier(3);
var numbers = [1, 2, 3]
console.log(x.weightNumbers.apply(x, numbers));
When the method you are calling .apply()
on needs to access instance data, then you MUST pass the appropriate object as the first argument so that the method has the right this
pointer to do its job as expected.