严格模式下函数直接调用时this为undefined且不报错,仅在访问其属性或方法(如this.name、this.sayhi())时抛typeerror;可通过bind/call/防护判断或箭头函数规避。

在严格模式下,函数直接调用时 this 值为 undefined,但不会“抛出异常”——这是常见误解。JavaScript 引擎不会因 this 是 undefined 而自动报错;异常只会在你**显式访问或操作 this 的属性/方法**,且 this 为 undefined(或 null)时触发。
严格模式下 this 的真实行为
启用严格模式("use strict")后,普通函数直接调用(如 foo())的 this 绑定为 undefined,而非非严格模式下的全局对象(window 或 globalThis)。这本身是合法的、静默的,不抛错。
什么时候会真正抛出异常?
异常发生在你试图对 undefined 执行需要对象上下文的操作,例如:
-
读取属性:
this.name→TypeError: Cannot read property 'name' of undefined -
调用方法:
this.sayHi()→TypeError: Cannot read property 'sayHi' of undefined(或直接TypeError: this.sayHi is not a function) -
赋值给只读属性(极少见):若
this是undefined,this.x = 1在严格模式下也会报TypeError
一个可复现的例子
下面代码在严格模式下运行会立即报错:
<script></script>"use strict";
function foo() {
console.log(this.name); // ← 这里触发 TypeError
}
foo(); // 直接调用 → this === undefined
如何避免或调试这类问题
- 检查函数是否被正确绑定:
foo.bind(obj)、obj.foo()、foo.call(obj)等 - 在函数开头加防护:
if (this == null) throw new Error("this must be bound"); - 使用箭头函数(无独立
this,继承外层作用域),但注意它不适用于需要动态this的场景(如事件处理器、原型方法) - 现代开发中,TypeScript 可通过
strictBindCallApply和类型标注提前发现潜在this问题
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











