严格模式下普通函数调用时this默认为undefined;需在函数或脚本顶部添加"use strict"启用,且call/apply/bind、对象方法调用等场景会改变this值。

在严格模式下,普通函数调用时 this 默认就是 undefined,无需额外操作 —— 这是严格模式的默认行为。
确保运行在严格模式中
只有整个函数体或整个脚本处于严格模式,该函数调用才会让 this 为 undefined。常见写法:
- 在函数顶部添加
"use strict";(推荐,作用域精准) - 或在脚本最开头写
"use strict";(影响整个脚本)
例如:
function foo() {<br> "use strict";<br> console.log(this); // undefined<br>}<br>foo(); // 普通调用
避免 this 被意外绑定
即使在严格模式下,也要注意以下情况会让 this 不是 undefined:
- 用
call/apply/bind显式传入值(哪怕传null或undefined,严格模式下仍保持原值) - 作为对象方法调用:
obj.method()→this指向obj - 被事件系统或框架调用(如 DOM 事件回调),
this由调用方决定
验证 this 确实为 undefined
可直接用全等判断:
function test() {<br> "use strict";<br> if (this === undefined) {<br> console.log("this is truly undefined");<br> }<br>}<br>test();
注意:不要用 if (!this),因为 undefined 是假值,但 0、""、false 也会触发,不准确。
对比非严格模式的区别
非严格模式下普通函数调用的 this 指向全局对象(浏览器中是 window,Node.js 中是 global)。严格模式正是为了消除这种隐式绑定,让 this 更可控、更符合直觉。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











