发布于 1年前

JavaScript在严格和非严格模式下,call()函数传递null或undefined的区别

Function.prototype.call()函数使用给定的this值和提供的参数来调用函数。

语法

function.call(thisArg, arg1, arg2, ...)

在非严格模式下,如果thisArg为null或者undefined,它们会被转换为全局的对象作为this的值,如Window。

非严格模式

function test(){         
     console.log(this);
 }
test.call(null); 
test.call(); 

在浏览器运行此代码,this输出都为Window

严格模式(use strict)

function test() {
  "use strict";
  console.log(this);
}
test.call(null); 
test.call(); 

在浏览器运行此代码,控制台分别输出this值为:

null
undefined
©2020 edoou.com   京ICP备16001874号-3