🎯箭头函数 vs. 常规函数(JavaScript)
Source: Dev.to

在 JavaScript 面试中,最常见的困惑来源之一是 this 在 箭头函数 与 普通函数 中的不同表现。如果你曾经想过为什么 this 有时会输出 undefined——本指南将为你彻底解释。
1️⃣ 普通函数 — this 是动态的
在 普通函数 中,this 的值取决于 函数的调用方式,而不是函数定义的位置。
const user = {
name: 'Richa',
greet: function () {
console.log(this.name);
}
};
user.greet(); // Richa
const greetCopy = user.greet;
greetCopy(); // ❌ undefined (or window.name in browsers)
为什么会这样
this 由调用上下文决定。当函数失去对象引用时,this 不再指向 user。
2️⃣ 箭头函数 — this 是词法的
箭头函数 没有 自己的 this。相反,它们 继承 来自外围作用域的 this。
const user = {
name: 'Richa',
greet: () => {
console.log(this.name);
}
};
user.greet(); // ❌ undefined
为什么?
箭头函数在全局作用域中创建,因此它继承的是全局的 this,而不是 user 对象。
✅ 正确的做法
当需要 this 指向对象时,请使用 普通方法:
const user = {
name: 'Richa',
greet() {
console.log(this.name);
}
};
user.greet(); // ✅ Richa
3️⃣ 最佳使用场景:普通函数内部的箭头函数
当在 方法或回调函数 中使用时,箭头函数表现出色,因为它们保持相同的 this 上下文。
const team = {
name: 'Frontend',
members: ['Richa', 'Jane'],
showMembers() {
this.members.forEach(member => {
console.log(`${member} is part of ${this.name}`);
});
}
};
team.showMembers();
// Richa is part of Frontend
// Jane is part of Frontend
如果在 forEach 中使用普通函数,this.name 将会是 undefined。
面试准备答案
- 普通函数 的
this是 动态 的——取决于调用方式。 - 箭头函数 的
this是 词法 的——它们从父作用域继承。
🎯 额外提示
这就是为什么箭头函数常用于 React 组件,因为你希望 this 保持一致。
关键要点
箭头函数不仅仅是更简短的写法——它们 保留上下文。
| 特性 | 普通函数 | 箭头函数 |
|---|---|---|
拥有自己的 this | ✅ 是 | ❌ 否 |
this 取决于调用位置 | ✅ 是 | ❌ 否 |
| 最适合用于对象方法 | ✅ 是 | ❌ 否 |
| 最适合用于回调函数 | ❌ 通常否 | ✅ 是 |
最后思考
一旦你理解了 动态 与 词法 this 的区别,你的代码将会变得:
- 更简洁 ✅
- 更易于推理 ✅
- 更少出错 ✅
箭头函数不仅仅是 节省语法 ——它们 保留上下文。 ⚡