ES6 箭头函数与普通函数的区别

掌握箭头函数:ES6 带来的函数革命

箭头函数是 ES6 引入的最受欢迎特性之一,但它不是普通函数的简单缩写。今天我们深入对比箭头函数与 function 关键字的本质区别。


📋 快速对比表

特性 普通函数 箭头函数
this 绑定 运行时动态绑定 词法作用域(定义时确定)
arguments ✅ 可用 ❌ 不可用,使用 ... 展开代替
构造函数 ✅ 可用 new ❌ 不能作为构造函数
隐式返回 ❌ 必须写 return ✅ 单表达式可省略 return
适合场景 方法、构造函数、需要动态 this 回调、简单计算、需要词法 this

1️⃣ this 绑定:最关键的坑

❌ 普通函数的 this "丢失"问题

// 对象方法中的回调
const obj = {
name: '张三',
friends: ['李四', '王五'],
showFriends: function() {
// ❌ this 会"丢失"指向 window/undefined
this.friends.forEach(function(friend) {
console.log(this.name + ' 和 ' + friend);
// 输出: undefined 和 李四
});
}
};

✅ 箭头函数的 this 继承外层

const obj = {
name: '张三',
friends: ['李四', '王五'],
showFriends: function() {
// ✅ this 保持指向 obj
this.friends.forEach(friend => {
console.log(this.name + ' 和 ' + friend);
// 输出: 张三 和 李四
});
}
};

关键理解:箭头函数的 this定义时就确定了,等于外层的 this,运行时不会改变。


2️⃣ 箭头函数真的没有 arguments

// ❌ 箭头函数:没有自己的 arguments
const sum = () => {
console.log(arguments);
// 报错或返回外层 arguments
};

// ✅ 推荐使用剩余参数替代
const sum = (...args) => {
return args.reduce((a, b) => a + b, 0);
};

3️⃣ 隐式返回:代码更简洁

// 普通函数
const double = function(x) {
return x * 2;
};

// 箭头函数隐式返回
const double = x => x * 2;

✅ 单表达式默认隐式返回
✅ 多行需要使用 {}return


4️⃣ 什么时候不能用箭头函数?

  • 对象方法:需要动态 this 指向调用者时
  • 事件处理器:需要 this 指向 DOM 元素
  • 构造函数:箭头函数不能使用 new
  • 需要 arguments某些兼容场景

🎯 最佳实践建议

  1. 优先使用箭头函数:简单回调、map/filter/reduce、Promise 链
  2. 保留普通 function:类方法、需要动态 this 的回调
  3. 混合写法:对象方法用 method() {} 简写,内部回调用箭头

---

参考:MDN - Arrow Functions | JavaScript.info

评论

发表评论

此博客中的热门博文

OpenClaw 救援机器人建设与演进全记录 - 从单点故障到双实例自愈体系

Lossless Claw:无损上下文管理插件分析报告

[Hello-Agents] Day 2: 第一章 初识智能体