Reputation: 73
When the this
value of Function.prototype.call()
& Function.prototype.apply()
can be null
or undefined
?
Take the example of the code below:
var numbers = [5, 6, 2, 3, 7];
var min = Math.min.apply(null, numbers);
Example from MDN Function.prototype.apply().
Edit: The original question has a third part and a different example:
When the
this
value of .call() & .apply() can benull
orundefined
or even none?Take the example of
Array.prototype.slice.call(auguements);
I thought there has no this value,but thanks to @guest271314 now I know that was stupid
Upvotes: 0
Views: 173
Reputation: 288590
It can be null
or undefined
only in strict mode.
In sloppy mode they will be ignored, and you will get the global object instead.
function logThis() {
console.log(this === window); // true :(
}
logThis.call(undefined);
logThis.call(null);
logThis.apply(undefined);
logThis.apply(null);
This is defined in OrdinaryCallBindThis, used by [[Call]]
- If thisMode is strict, let thisValue be thisArgument.
- Else
- if thisArgument is null or undefined, then
- Let thisValue be calleeRealm.[[globalThis]].
- Else
- Let thisValue be ToObject(thisArgument).
If you want to know if calling a function with a null
or undefined
this
value will break it, then you need to know what that function will attempt to do with the this
value.
In your example, Math.min
completely ignores the this
value, so it doesn't matter what value you pass. However, since it's a Math
method, it might make sense to pass Math
instead of null
or undefined
.
Math.min.apply(Math, [5, 6, 2, 3, 7]); // 2
Upvotes: 1