How to set null context in call function?

Quoting from MDN

if the method is a function in non-strict mode, null and undefined will be replaced with the global object and primitive values will be converted to objects.

This explains why you get an object when you call test.call(null);. When null is passed here, this inside test() will be global object Window.

For the desired behavior, use strict mode.

function test() {
  "use strict";
  if (this === null) {
    console.log("This is null");
  } else {
    console.log("This is Object");
  }
}
test.call(null);
test.call({});

Quoting from ES6 Specifications for strict mode

If this is evaluated within strict mode code, then the this value is not coerced to an object. A this value of null or undefined is not converted to the global object and primitive values are not converted to wrapper objects. The this value passed via a function call (including calls made using Function.prototype.apply and Function.prototype.call) do not coerce the passed this value to an object

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)