普通函数直接调用时,this指向全局对象(非严格模式)或undefined(严格模式),与“调用者”无关;箭头函数不绑定this,继承外层词法作用域的this值;call、apply立即执行并指定this,bind返回预设this的新函数。

普通函数调用时,this 指向全局对象或 undefined
在非严格模式下,直接调用函数(如 foo()),this 指向 window(浏览器)或 globalThis(Node.js);严格模式下则是 undefined。这和很多人直觉中“this 指调用者”不符,因为这里根本没“调用者对象”。
常见错误现象:
function say() {
console.log(this);
}
say(); // 浏览器中输出 window,严格模式下是 undefined你本想让 this 指向某个配置对象,结果它悄悄指向了全局,后续访问 this.apiKey 就报 Cannot read property 'apiKey' of undefined。
- 别依赖默认绑定,尤其在模块化代码或严格模式项目里
- 如果真需要全局上下文,显式传入
window或globalThis更安全 - 箭头函数不绑定
this,它沿用外层函数的this值——但这不是“修复”,只是绕过问题
call、apply、bind 的区别与适用场景
三者都用于手动指定函数执行时的 this,但时机和参数形式不同:
-
call(obj, arg1, arg2):立即执行,参数逐个列出 -
apply(obj, [arg1, arg2]):立即执行,参数以数组形式传入 -
bind(obj, arg1, arg2):返回新函数,this和部分参数被预设,不立即执行
性能影响:每次调用 bind 都创建新函数,频繁绑定(如渲染列表项时)可能引发内存或比较问题;call/apply 无此开销,适合一次性上下文切换。
典型使用场景:
const user = { name: 'Alice', age: 30 };
function introduce(greeting, suffix) {
console.log(`${greeting}, I'm ${this.name}${suffix}`);
}
introduce.call(user, 'Hi', '!'); // Hi, I'm Alice!
introduce.apply(user, ['Hello', '.']); // Hello, I'm Alice.
const greetAlice = introduce.bind(user, 'Hey');
greetAlice('?'); // Hey, I'm Alice?
事件处理器和回调中 this 丢失的根源与解法
DOM 事件监听器、setTimeout、数组方法(如 map、forEach)的回调函数,默认以普通函数方式调用,this 不继承外层对象。
立即学习“Java免费学习笔记(深入)”;
例如:
const button = document.querySelector('button');
const handler = {
name: 'clickHandler',
onClick() {
console.log(this.name); // 这里 this 是 button 元素,不是 handler 对象
}
};
button.addEventListener('click', handler.onClick); // ❌ this 指向 button
- 最稳妥:用箭头函数包装,或在绑定时用
bind:handler.onClick.bind(handler) - 现代写法:类中用属性初始化语法定义箭头函数方法,自动绑定:
onClick = () => { ... } - 避免在
addEventListener中直接传obj.method,除非你明确希望this是触发元素
箭头函数不能解决所有 this 问题
箭头函数没有自己的 this,它捕获的是**定义时所在词法作用域的 this**。如果外层作用域的 this 本身就不对,箭头函数只会固化这个错误。
反例:
const obj = {
value: 42,
regular() {
console.log(this.value); // 42 ✅
},
arrow: () => {
console.log(this.value); // undefined ❌ —— 外层是模块顶层,this 是 undefined(严格模式)
}
};
再比如,在构造函数或类方法中误用箭头函数作为原型方法,会导致 this 指向模块而非实例。
容易被忽略的一点:TypeScript 的 noImplicitThis 选项能提前暴露这类隐患,建议开启;但它的提示依赖类型标注,无法覆盖所有动态场景。











