讲解

箭头函数是 ES6 引入的简洁函数写法:(参数) => 返回值。单个参数时括号可省 x => x * 2;函数体只有一条返回语句时花括号和 return 都可省,这叫隐式返回;要隐式返回对象字面量,得用括号包住对象 (x) => ({ value: x }),否则花括号会被当成函数体。多行逻辑仍然写完整函数体加 return。

箭头函数最大的特点不是短,而是它没有自己的 this:箭头函数里的 this 永远等于它「定义处」外层作用域的 this(词法绑定),不受调用方式影响,也不能被 call/apply/bind 改变。这个特性完美解决了传统回调里 this 丢失的问题——定时器、事件回调、数组方法回调里的箭头函数都能稳定访问外层 this。代价是:箭头函数不适合当对象方法(this 不是该对象)、不能当构造函数(没有 prototype,new 会报错)、没有自己的 arguments。

选型经验:数组回调、Promise 链、事件处理里优先箭头函数;对象方法、需要动态 this 的场景用普通函数或方法简写。另一个小差别:箭头函数总是匿名的(虽然可以赋值给变量),调试时堆栈里的名字来自变量名推断。

示例

// 语法演进:从普通函数到最简箭头
const add1 = function (x) {
  return x + 1;
};
const add2 = (x) => {
  return x + 1;
};
const add3 = (x) => x + 1;
console.log(add1(1), add2(1), add3(1));

// 数组回调是箭头函数的主场
const nums = [1, 2, 3, 4, 5];
console.log('平方:', nums.map((n) => n * n));
console.log('偶数:', nums.filter((n) => n % 2 === 0));

// 隐式返回对象要加括号
const makeUser = (name) => ({ name, created: true });
console.log(makeUser('小明'));

// 箭头函数没有自己的 this:词法绑定外层
const timer = {
  seconds: 0,
  start() {
    const tick = () => {
      this.seconds++; // this 来自外层的 start 方法,即 timer
    };
    tick();
    tick();
  },
};
timer.start();
console.log('箭头函数保住了 this:', timer.seconds);

// 箭头函数不能 new
const NotConstructor = () => {};
try {
  new NotConstructor();
} catch (e) {
  console.log('new 箭头函数:', e.constructor.name);
}

常见坑

  • 用箭头函数当对象方法:const obj = { f: () => this.x } 里 this 不是 obj,是外层作用域的 this。对象方法用简写 f() {} 或普通函数。
  • 隐式返回对象忘加括号:x => { value: x } 把花括号当函数体,返回 undefined,是个高频笔误。
  • 试图 bind 箭头函数的 this:bind/call/apply 对箭头函数的 this 无效(第一个参数被忽略),传参功能仍在但 this 改不了。
  • 在箭头函数里用 arguments:箭头函数没有自己的 arguments,会拿到外层的。收集参数用 ...args。

小结

箭头函数简洁、隐式返回、词法 this 三大特性;回调场景首选,对象方法和构造函数别用。下一节讲作用域与变量提升,把 let/const/var 的行为差异彻底讲透。