函数
箭头函数
掌握箭头函数语法、this 绑定差异
箭头函数
箭头函数是 ES6 引入的更简洁的函数写法,但也有一些重要区别。
学完本章你将: 掌握箭头函数语法、this 绑定差异。
基本语法
javascript
// 传统写法
const add1 = function(a, b) {
return a + b;
};
// 箭头函数
const add2 = (a, b) => {
return a + b;
};
// 单行可省略 {} 和 return
const add3 = (a, b) => a + b;
// 单参数可省略 ()
const double = x => x * 2;
// 无参数需要 ()
const greet = () => "Hello!";
返回对象的注意
javascript
// ❌ 这样写会被当成函数体
// const createUser = (name) => { name: name };
// ✅ 用 () 包裹
const createUser = (name) => ({ name });
console.log(createUser("Alice")); // { name: "Alice" }
this 绑定 —— 核心区别
javascript
// 传统函数:this 指向调用者
const person1 = {
name: "Alice",
greet: function() {
console.log(this.name);
}
};
person1.greet(); // "Alice"
// 箭头函数:this 继承父作用域
const person2 = {
name: "Bob",
greet: () => {
console.log(this.name);
}
};
person2.greet(); // undefined(this 指向全局)
// 箭头函数的 this 优势:回调函数
const timer = {
name: "Timer",
start() {
setTimeout(function() {
console.log(this.name); // undefined
}, 100);
setTimeout(() => {
console.log(this.name); // "Timer" ✅
}, 100);
}
};
不能用作构造函数
javascript
const Person = (name) => {
this.name = name;
};
// const p = new Person("Alice"); // ❌ TypeError
// 传统函数可以
function PersonFunc(name) {
this.name = name;
}
const p = new PersonFunc("Alice"); // ✅
何时用箭头函数?
| 场景 | 推荐 |
|---|---|
| 简单回调 | 箭头函数 |
| 需要 this 的回调 | 箭头函数 |
| 对象方法 | 传统函数 |
| 构造函数 | 传统函数 |
| 事件处理器(需要 this) | 传统函数 |