this指向取决于调用方式而非定义位置;call/apply/bind可显式绑定且优先级最高;普通调用时非严格模式指向全局,严格模式为undefined;箭头函数无this,继承词法作用域this。

JavaScript 中 this 指向谁,取决于函数怎么被调用
不是看函数在哪定义,也不是看它写在哪个对象里,而是看执行时的「调用方式」。同一个函数,不同调用方式下 this 可能完全不同。
call、apply、bind 会显式绑定 this
这三个方法直接指定函数运行时的 this 值,优先级高于其他规则(除了箭头函数)。
-
func.call(obj, arg1, arg2):立即执行,this指向obj -
func.apply(obj, [arg1, arg2]):立即执行,参数以数组传入 -
const bound = func.bind(obj):返回新函数,this永远绑定为obj - 多次
bind无效,只有第一次生效
function logThis() {
console.log(this);
}
const obj = { name: 'test' };
logThis.call(obj); // { name: 'test' }
logThis.bind({ x: 1 }).call({ y: 2 }); // 仍然是 { x: 1 },第二次 call 不覆盖 bind 的 this
普通函数调用(非严格模式 vs 严格模式)
这是最容易出错的场景——没任何修饰地直接写 fn():
- 非严格模式下:
this指向window(浏览器)或global(Node.js) - 严格模式下:
this是undefined - ES6 模块默认启用严格模式,所以模块内直接调用函数时
this很可能是undefined
"use strict";
function foo() {
console.log(this); // undefined
}
foo();
箭头函数没有自己的 this
它不遵循上述任何规则,而是沿用定义时所在词法作用域的 this 值,且无法被 call/apply/bind 修改。
立即学习“Java免费学习笔记(深入)”;
- 常用于事件回调、定时器中避免
this丢失 - 不能用作构造函数(没有
prototype,调用new会报错) - 在对象方法中写箭头函数,
this不指向该对象,而是外层作用域
const obj = {
name: 'Alice',
regular() {
return this.name; // 'Alice'
},
arrow: () => {
return this.name; // undefined(全局中 this 没有 name)
}
};
真正麻烦的是嵌套函数 + 异步 + 类方法混合的场景,比如 setTimeout 里调用对象方法,或 React 类组件中事件处理函数忘记绑定 this。这时候别硬记规则,直接用 console.log(this) 看一眼最实在。











