call 和 apply 的第一个参数指定 this 绑定对象:非严格模式下 null/undefined 被转为全局对象(window/global),严格模式下保持原值;bind 行为相同;箭头函数不受影响。

在 JavaScript 中,call 和 apply 的第一个参数是用于指定函数内部 this 的绑定对象。当传入 null 或 undefined 时,JavaScript 会按严格模式和非严格模式分别处理,结果不同。
非严格模式下:null 和 undefined 被自动替换为全局对象
在非严格模式(即普通脚本或未加 "use strict" 的函数中),如果给 call 或 apply 传入 null 或 undefined 作为 thisArg,引擎会将其隐式转换为全局对象:
- 浏览器环境中,变成
window - Node.js 环境中,变成
global
例如:
function say() { console.log(this); }
say.call(null); // 浏览器中输出 window
say.call(undefined); // 同样输出 window严格模式下:null 和 undefined 会被原样保留为 this 值
在严格模式下,this 不再被自动装箱或替换。传什么就是什么:
分析 Java Spring Boot 后端 Controller 代码,自动生成 Markdown 格式的接口文档。当用户说“生成 Java 接口文档”、“生成 API 文档”、“从 Spring 代码生成文档”时触发。
-
call(null)→ 函数内this === null -
call(undefined)→ 函数内this === undefined
例如:
"use strict";
function checkThis() { console.log(this); }
checkThis.call(null); // 输出 null
checkThis.call(undefined); // 输出 undefined实际开发中要注意的细节
这类行为容易引发隐蔽 bug,尤其在工具函数或 polyfill 中:
- 不要假设
null一定变成window,需明确判断运行模式 - 写库或通用函数时,建议显式处理
null/undefined,比如用thisArg == null ? globalThis : thisArg -
bind的行为与call/apply一致,同样受严格模式影响
箭头函数不受影响
箭头函数没有自己的 this,所以 call 和 apply 无法改变它的 this 绑定,无论传入什么值(包括 null)都无效,始终沿用外层作用域的 this。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










