ES6 的箭头函数和普通函数有什么区别?
请全面对比箭头函数(Arrow Function)和普通函数(Function Declaration/Expression)的区别。
回答
古法程序员
| 特性 | 箭头函数 | 普通函数 |
|---|---|---|
| this 绑定 | 词法绑定(继承外层 this) | 动态绑定(取决于调用方式) |
| arguments | ❌ 没有(可用 rest 参数替代) | ✅ 有 arguments 对象 |
| new 调用 | ❌ 不能作为构造函数(TypeError) | ✅ 可以被 new 调用 |
| prototype | ❌ 没有 prototype 属性 | ✅ 有 prototype |
| yield | ❌ 不能作为 Generator | ✅ 可以 |
| 语法简洁 | (x) => x * 2 | function(x) { return x * 2; } |
| 隐式 return | ✅ 单表达式无需 return | ❌ |
| call/apply/bind | 无法改变 this | ✅ 可改变 this |
特殊点:
- 箭头函数不能用作对象方法(除非该方法在 class 中作为字段初始化,此时 this 绑定到实例)
- 箭头函数没有
super、new.target绑定 - 箭头函数不能使用
prototype属性(没有[[Construct]])
选择建议:
- 需要动态 this → 普通函数
- 需要 arguments → 普通函数或 rest 参数
- 需要构造函数 → 普通函数
- 回调函数、短表达式、固定 this → 箭头函数