箭头函数(Arrow Function)是 ES6 引入的一种简洁的函数定义方式,核心优势是语法更简洁、不绑定自己的 this(继承外层作用域的 this),同时没有 arguments、prototype 等特性。下面详细讲解其用法和简化语法。
一、基础语法对比
先通过对比普通函数和箭头函数,理解核心结构:
// 普通函数(函数表达式) const add = function(a, b) { return a + b; }; // 箭头函数(基础形式) const add = (a, b) => { return a + b; };箭头函数的核心结构:参数 => 函数体
二、核心简化语法(重点)
箭头函数的简化分为参数简化和函数体简化,可根据场景逐步精简:
1. 参数简化
| 场景 | 语法示例 | 说明 |
|---|---|---|
| 无参数 | () => { ... } | 必须保留空括号 |
| 单个参数 | a => { ... } | 可省略括号(推荐简化) |
| 多个参数 | (a, b, c) => { ... } | 必须保留括号 |
| 解构参数 | ({ name, age }) => { ... } | 解构仍需括号 |
示例:
// 无参数 const sayHi = () => { console.log('Hi!'); }; // 单个参数(简化括号) const double = num => { return num * 2; }; // 多个参数 const sum = (a, b, c) => { return a + b + c; }; // 解构参数 const getUserInfo = ({ name, age }) => { return { name, age }; };2. 函数体简化
如果函数体只有一行返回语句,可省略{}和return(核心简化):
| 场景 | 语法示例 | 说明 |
|---|---|---|
| 单行返回值 | a => a * 2 | 省略 {} 和 return |
| 单行返回对象 | a => ({ id: a, name: 'test' }) | 对象需用 () 包裹(避免歧义) |
| 多行函数体 | a => { const b = a + 1; return b; } | 必须保留 {} 和 return |
示例:
// 单行返回值(最简形式) const double = num => num * 2; // 单行返回对象(注意括号) const createUser = id => ({ id, name: 'User' }); // 多行函数体(不可简化) const calculate = (a, b) => { const sum = a + b; const product = a * b; return sum + product; };三、核心应用场景 1:数组方法的回调函数(最常用)
数组的map/filter/reduce/forEach/sort等方法的回调函数,逻辑通常简洁(单行 / 少量逻辑),箭头函数能极大简化代码,且无需关注 this 绑定(数组方法回调的 this 本身无特殊意义)。
示例:
const arr = [1, 2, 3, 4]; // 1. map:数据转换(最简写法) const doubleArr = arr.map(num => num * 2); // [2,4,6,8] // 2. filter:数据过滤 const evenArr = arr.filter(num => num % 2 === 0); // [2,4] // 3. reduce:聚合计算 const sum = arr.reduce((acc, cur) => acc + cur, 0); // 10 // 4. sort:自定义排序 const users = [{ age: 20 }, { age: 18 }]; users.sort((a, b) => a.age - b.age); // 按年龄升序四、核心应用场景 2:异步 / 定时器回调(固定 this)
定时器(setTimeout/setInterval)、Promise 回调、事件监听异步处理等场景,普通函数会导致this指向混乱,箭头函数可继承外层作用域的this,无需手动绑定(如bind/ 保存that)。
示例 1:定时器
const user = { name: "张三", fetchData() { // 普通函数:this 指向 window/global setTimeout(function() { console.log(this.name); }, 100); // undefined // 箭头函数:this 继承 fetchData 的 this(指向 user) setTimeout(() => { console.log(this.name); }, 100); // 张三 } }; user.fetchData();示例 2:Promise 回调
class Order { constructor(price) { this.price = price; } calculate() { // Promise 回调用箭头函数,继承 this 指向 Order 实例 Promise.resolve().then(() => { console.log(this.price * 0.8); // 正确访问实例属性 }); } } new Order(100).calculate(); // 80五、核心应用场景 3:纯函数 / 简单逻辑函数
仅做数据计算、无副作用、无需动态this的简单函数(如工具函数),用箭头函数更简洁,语义更聚焦逻辑。
示例:
// 工具函数:判断是否为数字 const isNumber = val => typeof val === "number" && !isNaN(val); // 工具函数:格式化时间(单行逻辑) const formatTime = time => new Date(time).toLocaleString(); // 组件内简单计算(如 React/Vue 中) const getTotal = (list) => list.reduce((acc, item) => acc + item.count, 0);六、核心应用场景 4:解构 / 剩余参数结合(简化参数处理)
箭头函数适配 ES6 解构、剩余参数语法,能进一步简化参数接收逻辑,尤其适合接收对象 / 数组参数的场景。
示例:
// 解构对象参数 const getUserInfo = ({ name, age }) => ({ name, age, id: Date.now() }); getUserInfo({ name: "李四", age: 25 }); // { name: '李四', age: 25, id: 17... } // 剩余参数接收任意参数 const merge = (...args) => args.reduce((acc, cur) => ({ ...acc, ...cur }), {}); merge({ a: 1 }, { b: 2 }); // { a:1, b:2 }七、核心应用场景 5:React/Vue 组件内的回调(简化写法)
在 React 函数组件、Vue 组件的 methods/setup 中,箭头函数可简化事件回调、生命周期 / 钩子函数的写法,同时避免 this 绑定问题(React 类组件中尤甚)。
示例 1:React 类组件(避免 bind)
class Button extends React.Component { handleClick = () => { // 箭头函数作为类属性,this 固定指向组件实例 console.log(this.props.text); }; render() { return <button onClick={this.handleClick}>点击</button>; } }示例 2:Vue setup 中的回调
<script setup> import { ref } from 'vue'; const count = ref(0); // 箭头函数简化点击回调 const handleAdd = () => { count.value += 1; }; </script> <template> <button @click="handleAdd">计数:{{ count }}</button> </template>八、绝对不适合的场景(避坑关键)
箭头函数的 “特性阉割” 决定了以下场景必须用普通函数:
| 不适合的场景 | 原因 | 正确做法 |
|---|---|---|
| 对象方法 | 箭头函数 this 指向外层(如 window),而非对象本身 | 用普通函数定义对象方法 |
| 构造函数 | 无 prototype,不能用 new 调用 | 用普通函数 / 类(class) |
| 生成器函数 | 不能使用 yield 关键字 | 用function*定义生成器 |
| 事件处理函数 | 需动态 this(指向事件源),箭头函数 this 固定 | 用普通函数,或手动传事件源 |
| 需 arguments 场景 | 箭头函数无 arguments,若需伪数组需手动处理 | 用普通函数,或剩余参数...args |
反例(错误用法):
// 1. 对象方法用箭头函数(错误) const obj = { name: "王五", sayHi: () => console.log(this.name) // this 指向 window,输出 undefined }; obj.sayHi(); // 2. 构造函数用箭头函数(错误) const Person = (name) => { this.name = name; }; new Person("赵六"); // TypeError: Person is not a constructor // 3. 事件处理函数用箭头函数(错误) document.querySelector('button').addEventListener('click', () => { console.log(this); // 指向外层 this,而非按钮元素 });九、总结
1、简化语法速记
| 原始写法 | 简化后 | 适用场景 |
|---|---|---|
(a) => { return a * 2; } | a => a * 2 | 单个参数 + 单行返回 |
() => { return 1; } | () => 1 | 无参数 + 单行返回 |
(a,b) => { return a+b; } | (a,b) => a+b | 多个参数 + 单行返回 |
(a) => { return {a}; } | a => ({a}) | 单行返回对象 |
箭头函数的核心是简洁 + 继承 this,优先用于回调函数(如数组方法、定时器),避免用于构造函数、对象方法等场景。
2、箭头函数应用场景速记
| 适用场景 | 核心优势 | 示例 |
|---|---|---|
| 数组回调(map/filter) | 语法极简,无需关注 this | arr.map(num => num * 2) |
| 异步 / 定时器回调 | 固定 this,避免指向混乱 | setTimeout(() => { ... }, 100) |
| 纯工具函数 | 简洁聚焦逻辑 | const isNumber = val => typeof val === 'number' |
| 解构 / 剩余参数处理 | 适配 ES6 语法,简化参数 | const fn = ({ a }) => a * 2 |
| 组件内简单回调(React/Vue) | 简化写法,固定 this | 类组件事件回调、setup 内函数 |
核心原则:只要不需要 “动态 this”“构造能力”“生成器 /yield”,且逻辑简洁,优先用箭头函数;反之用普通函数。