箭头函数(ES6)
箭头函数是函数简写语法 ,() => {},和普通函数行为差异很大,是 JS 进阶重点。
一、基础语法
1. 完整写法
js
// 普通函数
function fn(a, b) {
return a + b;
}
// 等价箭头函数
const fn = (a, b) => {
return a + b;
};
2. 简写规则(常用)
- 只有一个形参:可省略括号
js
const fn = x => x * 2;
- 函数体只有一行 return 代码 :可省略
{}和return
js
// 单行返回,直接写表达式
const add = (a, b) => a + b;
- 无参数:括号不能省
js
const say = () => "hello";
- 单行返回对象 :必须用小括号包裹
js
// 错误:{} 会被当成函数体
// const getObj = () => { name: "zs" };
// 正确
const getObj = () => ({ name: "张三" });
二、核心特性(重点,面试必考)
1. 没有自身 this
箭头函数的 this 继承外层最近一层作用域的 this ,永远不会改变。
普通函数 this 由调用方式决定,二者最大区别。
示例:
js
const obj = {
name: "李四",
// 普通函数:this → obj
fn1() {
console.log(this.name);
},
// 箭头函数:this 继承外层(全局/window)
fn2: () => {
console.log(this.name);
}
};
obj.fn1(); // 李四
obj.fn2(); // undefined
实用场景:解决定时器 this 指向问题
js
const person = {
name: "小明",
say() {
// 箭头函数 this 继承外层 say 函数的 this
setTimeout(() => {
console.log(this.name); // 小明
}, 1000);
}
};
person.say();
2. 没有 arguments 对象
箭头函数内部不存在 arguments,要用就用剩余参数 ... 替代:
js
// 箭头函数 用 ...rest 接收所有参数
const fn = (...rest) => {
console.log(rest);
};
fn(1, 2, 3); // [1,2,3]
3. 不能作为构造函数
不能使用 new 调用,没有 prototype 原型:
js
const Person = () => {};
// new Person(); // 报错
4. 不能使用 yield
不能用作生成器函数(function*)。
5. 不绑定 super
不能在类的方法中配合 super 使用。
三、使用场景 & 禁忌
✅ 适合使用箭头函数
- 简短回调函数(数组方法:
map/filter/forEach)
js
const arr = [1,2,3];
const res = arr.map(item => item * 10);
console.log(res); // [10,20,30]
- 定时器、事件回调,需要沿用外层
this - 简单工具函数、一行计算逻辑
❌ 不建议使用箭头函数
- 对象方法(会改变 this,拿不到对象自身属性)
- 类的原型方法
- 需要使用 arguments、new、yield 的场景
- 函数体逻辑复杂、多行代码(可读性变差)
四、this 速记口诀
普通函数:this 看调用,谁调用指向谁
箭头函数:this 看定义,继承外层 this