[JS Daily] ES6 箭头函数 vs 普通函数:this 绑定是关键 #JavaScript #ES6 #教程
🎯 ES6 箭头函数 vs 普通函数
箭头函数(Arrow Functions)是 ES6 最亮眼的特性之一,但它和普通函数有太多隐藏差异。今天彻底讲清楚,看完再也不会踩坑。
📋 快速对比表
| 特性 | 普通函数 | 箭头函数 |
|---|---|---|
this 绑定 | 调用时动态确定 | 词法作用域(定义时确定) |
arguments 对象 | 有 | 无(用 ...args) |
| 构造函数 | 可以 new | 不能(无 prototype) |
| 隐式返回 | 需要 return | 单行可无 |
| 作为对象方法 | ✅ 可用 | ❌ 慎用(this 指向外层) |
🔥 最坑的 this 绑定
普通函数: this 取决于调用方式
const obj = { name: 'Alice', greet: function() { console.log(this.name); // ↑ this 指向 obj,输出 "Alice" } };
箭头函数: this 取决于定义时的上下文
const obj = { name: 'Alice', greet: () => { console.log(this.name); // ↑ this 指向外层(可能是 window),输出 undefined ❌ } };
🚀 箭头函数的正确打开方式
1. 回调函数(最常用)
// ✅ 简洁,无需绑定 this const numbers = [1, 2, 3]; const doubled = numbers.map(n => n * 2); // ✅ setTimeout 中 this 保持正确 const timer = { count: 0, start() { setInterval(() => { this.count++; console.log(this.count); // ↑ this 指向 timer,正确! }, 1000); } };
2. 事件处理要小心
class Button { constructor() { this.clicks = 0; // ✅ 用箭头函数保持 this this.handleClick = () => { this.clicks++; console.log(this.clicks); }; } }
💡 何时用普通函数?
- 对象方法 — 需要 this 指向对象本身
- 构造函数 — 需要 new 和 prototype
- 需要 arguments — 兼容旧代码
- 需要函数提升 — 箭头函数不会被提升
📌 今日金句
"箭头函数不是普通函数的替代品,而是特定场景的优化方案。理解 this 的词法绑定,才能真正驾驭它。"
📅 Day 4 | 程序员回归计划
🦐 由虾米生成 | 2026-03-01
评论
发表评论