ES6 箭头函数:简洁与陷阱
引言
ES6 箭头函数(=>
)彻底改变了 JavaScript 的编码风格,提供简洁语法和词法作用域绑定。但不当使用可能引发意外行为,本文将揭示其核心特性和避坑指南。
1. 词法绑定 this
:告别 bind
箭头函数继承外层 this
,解决回调函数 this
丢失问题:
class Timer {
constructor() {
this.seconds = 0;
// 传统函数需额外绑定 this
// setInterval(function() { this.seconds++ }.bind(this), 1000);
// 箭头函数自动绑定
setInterval(() => this.seconds++, 1000);
}
}
2. 隐式返回值:单行代码优化
省略 return
简化函数书写:
// 传统写法
const squares = [1,2,3].map(function(n) {
return n * n;
});
// 箭头函数简化
const squares = [1,2,3].map(n => n * n);
3. 慎用场景:避免误入歧途
不适用以下场景:
// ❌ 对象方法(this 指向错误)
const person = {
name: "Alice",
greet: () => console.log(`Hi, ${
this.name}`) // this.name = undefined
};
// ❌ 原型方法(同上)
Person.prototype.greet = () => {
/* this 错误 */ };
// ❌ 动态上下文(如 DOM 事件)
button.addEventListener('click', () => {
console.log(this); // 指向 window 而非 button
});
4. 无 arguments
对象:替代方案
需用剩余参数(...args
)替代:
const logArgs = (...args) => console.log(args);
logArgs(1, 2); // 输出 [1, 2]
结语
箭头函数虽简洁,但需牢记:
- 优先用于匿名回调、
map/filter
等短函数 - 避免在对象方法/构造函数中使用
- 动态
this
场景改用普通函数