非严格模式下,JavaScript将null或undefined的thisArg自动替换为全局对象(如浏览器中的window),这是ES5+规范明确规定的;严格模式下则保持原值。

在非严格模式下,JavaScript中显式将 this 绑定为 null(例如通过 call(null)、apply(null) 或 bind(null)),引擎会自动把 null 替换为全局对象 —— 浏览器环境中就是 window。
为什么 null 会被替换成 window
这是 ECMAScript 规范明确规定的:当以非严格模式调用函数,并且传入的 thisArg 是 null 或 undefined 时,实际执行时会把 this 设为全局对象。
- 规范依据:ES5+ 中
Invoke和Call算法 步骤 6:若thisArg是null或undefined,则令thisValue为全局对象 - 浏览器中全局对象是
window(或self),Node.js 中是global - 这个替换只发生在非严格模式;严格模式下
this就真的保持为null
常见触发场景示例
以下写法在非严格模式下都会让函数内部的 this 指向 window:
function foo() { console.log(this === window); } foo.call(null); // true[1,2,3].map(function(x) { return this; }, null); // 返回 [window, window, window]const bound = function() { return this; }.bind(null); bound(); // window
如何验证 this 是否指向 window
可以在函数内做简单判断:
立即学习“Java免费学习笔记(深入)”;
- 检查
this === window(浏览器环境) - 打印
this并观察控制台输出是否显示Window对象 - 访问
this.document或this.alert等仅属于window的属性/方法(非严格模式下不会报错)
注意 strict mode 下行为完全不同
只要函数处于严格模式(函数体顶部有 "use strict";),null 就不会被替换:
function foo() { "use strict"; console.log(this); } foo.call(null); // null- 箭头函数不绑定
this,所以不受此规则影响,它继承外层作用域的this


















