JavaScript中this在函数调用时动态确定,受普通调用、方法调用、构造调用、显式绑定四种方式影响;箭头函数无this,继承外层普通函数的this值。
JavaScript 中的 this 容易混淆,根本原因在于它**不绑定在函数定义时,而是在函数调用时动态确定**,且规则看似简单、实则受调用方式多重影响。同一个函数,换一种调用写法,this 就可能指向完全不同对象。
理解 this 的核心是看函数「怎么被调用」:
fn()):非严格模式下 this 指向全局对象(浏览器中是 window),严格模式下为 undefined;obj.method()):this 指向点号前的对象(obj);new Fn()):this 指向新创建的实例;call / apply / bind):this 由第一个参数强制指定。箭头函数不绑定 this,它会沿作用域链向上查找外层普通函数的 this 值,并永久固定——这既是它的优势(避免手动绑定),也是陷阱(无法用 call 改变)。
例如:const obj = {
name: 'Alice',
normal() { console.log(this.name); },
arrow: () => console.log(this.name)
};
obj.normal(); // 'Alice'
obj.arrow(); // undefined(this 指向全局或模块顶层)
handler = () => {...}):自动绑定实例,避免 React 等框架中事件处理器丢失 this;arr.forEach(cb, this)),简洁安全。setTimeout(obj.method, 100)
),改用 bind 或箭头函数包装;undefined 而非意外指向 window);no-invalid-this)辅助检测潜在问题。