如何在调用函数中设置空上下文?

Obe*_*uel 46 javascript jquery

function test(){         
     if(this === null){
        console.log("This is null");
     }else{
         console.log("This is Object");
     }
 }
test.call(null);
test.call({});
Run Code Online (Sandbox Code Playgroud)

输出:

这是对象.

这是对象.

但我期待输出:

这是空的.

这是对象.

为什么Null没有设置在上下文中?

Tus*_*har 59

引自MDN

如果该方法是在非严格模式的功能,null以及undefined将与全局对象被替换和原始值将被转换为对象.

这解释了为什么在打电话时得到一个物体test.call(null);.当null在这里传递时,this里面test()将是全局对象Window.

对于所需的行为,请使用严格模式.

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

引用ES6规格的严格模式

如果this在严格模式代码中进行评估,则该this值不会强制转换为对象.甲this的值nullundefined不转换为全局对象和原始值不被转换为包装器的对象.this通过函数调用传递的值(包括使用Function.prototype.apply和进行的调用Function.prototype.call)不会强制将此值传递给对象