箭头函数写法fn => expr省略了 return 与大括号,是写 map/filter 回调的首选。更重要的是语义差异:箭头函数没有自己的 this,它从外层(定义处)继承 this;也没有自己的 arguments 和 prototype,不能用 new 调用。
这条「继承 this」的特性解决了回调里 this 丢失的老问题——以前要 const self = this 或 bind。但对象的字面量方法、需要动态 this 的场景(DOM 事件处理函数、构造函数原型方法)不适合用箭头函数,此时 this 语义会适得其反。
const nums = [1, 2, 3]; nums.map(n => n * 2); // [2,4,5] nums.filter(n => n > 1); // [2,3] // this 继承:定时器里也拿得到外层 this const timer = { count: 0, start() { setInterval(() => this.count++, 1000); // this 指向 timer }, }; // 反面教材:对象字面量用箭头函数,this 指向外层而不是 obj const obj = { name: 'x', say: () => console.log(this.name) };