Hao Zonggang
Hao Zonggang

Reputation: 73

When the this value of .call() & .apply() can be `null` or `undefined`?

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 be null or undefined 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

Answers (1)

Oriol
Oriol

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]]

  1. If thisMode is strict, let thisValue be thisArgument.
  2. Else
    1. if thisArgument is null or undefined, then
      1. Let thisValue be calleeRealm.[[globalThis]].
    2. Else
      1. 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

Related Questions