箭头函数更简洁,但真正的区别在于绑定行为,而不仅仅是语法。
js
const regular = function () {};
const arrow = () => {};
const short = x => x * 2; // implicit return for one expression
关键区别
1. 没有自己的 this — 箭头函数从周围的作用域继承 this。这是最重要的区别,也是为什么它们适合用于回调:
js
const timer = {
seconds: 0,
start() {
setInterval(() => this.seconds++, 1000); // ✅ `this` is timer
// a regular function here would have its own `this` (undefined) → bug
},
};
2. 没有 arguments 对象 — 改用 rest 参数:
js
const sum = (...args) => args.reduce((a, b) => a + b, 0);
3. 不能用作构造函数 — new arrow() 会抛出错误,它们没有 prototype。
何时不要使用箭头函数
js
const obj = {
name: "Ann",
greet: () => `Hi ${this.name}`, // ❌ `this` is NOT obj (it's outer scope)
greet2() { return `Hi ${this.name}`; }, // ✅ method needs dynamic `this`
};
不要为对象方法使用箭头函数(它们不会绑定到对象),或者当你需要动态 this/arguments 时(依赖 this 为元素的事件处理程序)。
为什么这很重要
对于回调和简短函数(其中继承 this 是你想要的)使用箭头函数;对于方法、构造函数和原型方法使用常规函数。
