箭头函数没有自己的 this,它会继承定义时外层作用域的 this,且终生不变。
| 特性 | 普通函数 | 箭头函数 |
|---|---|---|
this来源 | 调用时确定(谁调用指向谁) | 定义时捕获外层this |
| 能否被改变 | 可以通过call/apply/bind改变 | 不能,始终绑定定义时的this |
| 作为构造函数 | 可以new | 不可以 |
| 严格模式影响 | 严格模式下this可能为undefined | 不受影响 |
对象字面量不构成独立作用域
const obj = { name: 'Alice', say: () => { console.log(this.name); // this 指向定义时的上下文(通常是 window/global) } }; obj.say(); // undefined(或全局的 name)原因:say 定义在对象字面量中,但对象字面量不构成独立作用域,外层是全局作用域。
this 是不是按钮
// ❌ 错误:箭头函数导致 this 不是按钮 button.addEventListener('click', () => { this.classList.add('active'); // this 是外层作用域,不是 button }); // ✅ 正确:普通函数,this 指向触发事件的元素 button.addEventListener('click', function() { this.classList.add('active'); });什么时候该用箭头函数?
| 适合用 | 不适合用 |
|---|---|
需要保留外层this的回调(如setTimeout、map、forEach) | 需要动态this的对象方法 |
| 简短的函数表达式 | 需要作为构造函数 |
| 链式调用中的回调 | 需要arguments对象(箭头函数没有) |
function Timer() { this.seconds = 0; // 箭头函数保留 Timer 实例的 this setInterval(() => { this.seconds++; console.log(this.seconds); }, 1000); } const t = new Timer(); // 正常累加,不会指向 window,而是指向实例