JavaScript 中的 this 指向函数调用时的执行上下文对象,严格模式下普通函数独立调用时为 undefined,箭头函数无自身 this,call/apply/bind 可显式绑定,new 调用时指向新实例,事件监听中 this 默认为触发元素。

JavaScript 中的 this 不是指“函数自己”或“定义时的作用域”,而是**函数被调用时的执行上下文对象**——它完全取决于函数怎么被调用,而不是怎么被声明。
为什么 this 在普通函数里经常是 undefined(严格模式)?
在严格模式下,全局环境中直接调用函数(如 foo()),this 不再默认绑定到 window 或 globalThis,而是明确设为 undefined。这是为了暴露错误,避免隐式绑定带来的歧义。
- 非严格模式:
this指向window(浏览器)或globalThis(Node.js) - 严格模式:
this是undefined—— 这是标准行为,不是 bug - 箭头函数没有自己的
this,它沿用外层函数作用域的this值,且无法被call/apply/bind修改
call、apply 和 bind 怎么影响 this?
这三个方法都用于显式指定函数运行时的 this 值,但调用时机和返回结果不同:
-
func.call(obj, arg1, arg2):立即执行,参数逐个传入 -
func.apply(obj, [arg1, arg2]):立即执行,参数以数组形式传入 -
func.bind(obj, arg1):返回一个新函数,this被永久绑定为obj,后续调用不再受调用方式影响 - 注意:
bind绑定后无法被再次覆盖(除非用new调用,见下条)
构造函数中 this 指向什么?
用 new 调用函数时,JS 引擎会自动创建一个空对象,并把 this 绑定到该对象上;如果函数显式返回一个对象,则 this 的绑定结果会被忽略(返回值优先)。
立即学习“Java免费学习笔记(深入)”;
function Person(name) {
this.name = name; // this 指向新创建的实例
return { custom: true }; // 返回对象 → new 表达式结果就是这个对象
}
const p = new Person('Alice');
console.log(p.custom); // true
console.log(p.name); // undefined
- 没返回值或返回原始值(
string/number/etc)→this对象作为返回值 - 返回对象 → 忽略
this,以返回对象为准 - 箭头函数不能用
new调用,会抛出TypeError: xxx is not a constructor
事件监听器里的 this 为什么有时不是预期对象?
DOM 事件回调中,this 默认指向触发事件的元素(event.currentTarget),但容易在异步或箭头函数中丢失:
- 用
element.addEventListener('click', handler)→handler中的this是element - 若
handler是箭头函数 →this取外层作用域,通常不是 DOM 元素 - 若
handler被解构或赋值给变量(如const fn = obj.handleClick)→ 调用时失去原始this,需用bind或事件回调中显式传参
最稳妥的方式是直接使用 event.currentTarget 或 event.target,而非依赖 this。










