call、apply、bind传入null/undefined时,非严格模式下this自动绑定全局对象(window或global),严格模式下保持原值(null/undefined)。

在 JavaScript 显式绑定(即使用 call、apply 或 bind)时,如果传入 null 或 undefined 作为第一个参数(即期望的 this 值),它们会被自动替换为全局对象(非严格模式下)或保持为 null/undefined(严格模式下)。
非严格模式下的默认转换
当在非严格模式下调用 func.call(null) 或 func.apply(undefined),JavaScript 引擎会把 null 和 undefined 视为“未指定 this”,进而将 this 绑定到全局对象(浏览器中是 window,Node.js 中是 global)。
function foo() { return this; }foo.call(null); // window(非严格模式)foo.apply(undefined); // window(非严格模式)
严格模式下保持原值
在严格模式中,this 不再被自动装箱,传入什么就是什么:
"use strict"; function foo() { return this; }foo.call(null); // nullfoo.apply(undefined); // undefined- 此时若尝试访问
this.xxx会直接报错(如Cannot read property 'xxx' of null)
安全处理建议
为避免意外行为,推荐显式控制 this 值:
- 不依赖隐式转换,始终传入明确的对象(如空对象
{}或自定义上下文) - 封装调用逻辑,提前校验并归一化:
const safeThis = obj == null ? {} : obj;fn.call(safeThis, ...args); - 在工具函数或库中统一处理,例如 Lodash 的
_.bind内部会避免传入null/undefined作为thisArg
bind 的特殊情况
bind 返回的新函数在调用时仍遵循上述规则。但注意:一旦用 bind 绑定了 null 或 undefined,该绑定不可被后续的 call/apply 覆盖(硬绑定优先级最高):
const bound = foo.bind(null);bound.call({x:1}); // this 仍是 null(非严格模式下仍转为 window)- 所以
bind(null)实际上等价于bind()或bind(undefined),效果一致
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











