箭头函数入门指南
一句话理解
箭头函数 => 是 function 的简写,相当于把 function 关键字替换成一个箭头。
基础写法演变
// 原始函数
function add(a, b) {
return a + b;
}
// 箭头函数
const add = (a, b) => {
return a + b;
};
// 更简写(只有一行 return 时可以省略 {} 和 return)
const add = (a, b) => a + b;
三种常见写法
1. 无参数 → 必须加空括号
const hello = () => console.log('你好');
hello(); // 你好
2. 一个参数 → 可以省略括号
// 完整写法
const double = (x) => x * 2;
// 简写(一个参数时可省略括号)
const double = x => x * 2;
double(3); // 6
3. 多个参数 → 必须加括号
const add = (a, b) => a + b;
add(1, 2); // 3
函数体 写法规则
情况一:单行表达式(自动 return)
const square = x => x * x;
// 相当于 function square(x) { return x * x; }
square(4); // 16
情况二:多行语句(必须加 {} 和 return)
const process = (a, b) => {
const sum = a + b;
const product = a * b;
return sum > product ? sum : product;
};
情况三:返回对象(必须加括号)
// ❌ 错误:{} 会被当成函数体
const createUser = (name, age) => { name: name, age: age };
// ✅ 正确:加 () 表示返回的是对象
const createUser = (name, age) => ({ name, age });
createUser('张三', 25); // { name: '张三', age: 25 }
箭头函数 vs 普通函数
| 对比项 | 箭头函数 | 普通函数 |
|---|---|---|
| 写法 | 简洁 => |
冗长 function |
this |
从外层继承,不绑定自己的 this | 根据调用方式决定 this |
arguments |
❌ 没有 | ✅ 有 |
new 调用 |
❌ 不能用作构造函数 | ✅ 可以 |
prototype |
❌ 没有 | ✅ 有 |
this 绑定的区别(重要!)
// 普通函数:this 取决于谁调用
const obj1 = {
name: '对象1',
greet: function() {
console.log(this.name);
}
};
obj1.greet(); // 对象1
// 箭头函数:this 从外部作用域继承
const obj2 = {
name: '对象2',
greet: () => {
console.log(this.name); // this 指向全局/window
}
};
obj2.greet(); // undefined(在浏览器中是 window.name)
实际应用场景:回调函数中保留外层 this
// 普通函数需要保存 this
const timer1 = {
count: 0,
start: function() {
const self = this;
setInterval(function() {
self.count++;
}, 1000);
}
};
// 箭头函数自动继承 this
const timer2 = {
count: 0,
start: function() {
setInterval(() => {
this.count++; // 这里的 this 指向 timer2
}, 1000);
}
};
什么时候不能用箭头函数?
1. 作为对象方法(需要访问 this)
const user = {
name: '小明',
// ❌ 错误:this 不指向 user
sayHi: () => `我是${this.name}`,
// ✅ 正确:使用普通函数
sayHi() {
return `我是${this.name}`;
}
};
2. 构造函数
// ❌ 错误:箭头函数不能 new
const Person = (name) => {
this.name = name;
};
new Person('小明'); // TypeError
// ✅ 正确:使用普通函数
function Person(name) {
this.name = name;
}
3. 需要 arguments 对象
// ❌ 错误:箭头函数没有 arguments
const sum = () => {
console.log(arguments); // ReferenceError
};
// ✅ 正确:使用普通函数或剩余参数
const sum = (...args) => {
console.log(args); // [1, 2, 3]
};
sum(1, 2, 3);
实战:从普通函数到箭头函数
// 原始版本
const numbers = [1, 2, 3, 4, 5];
const doubled = numbers.map(function(num) {
return num * 2;
});
// 箭头函数版本
const doubled = numbers.map(num => num * 2);
// 更复杂的例子
const result = numbers
.filter(n => n % 2 === 0) // 偶数
.map(n => n * 10) // 乘以10
.reduce((sum, n) => sum + n); // 求和
console.log(result); // 60 (20 + 40)
总结
箭头函数 = 更短的写法 + 没有自己的 this/arguments
适合简单回调、数组操作,不适合对象方法和构造函数。
