JavaScript 词条目录
前端Wiki/JavaScript/基础/函数

箭头函数

箭头函数是 ES6 的简写语法,最大价值在于「短」:参数只有一个时可省括号,函数体只有一句 return 时可省大括号和 return,配合 map、filter 这类数组方法写出来的代码非常简洁。

几个语法细节:函数体只有一句且是返回值,写 x => x * 2;多行逻辑必须写大括号并显式 return;返回对象字面量时要给对象加圆括号(() => ({ a: 1 })),否则大括号会被当成函数体。

箭头函数和普通函数最重要的行为差异是:它没有自己的 this,而是沿用定义时外层的 this。这使得它在回调场景里不会丢失 this 指向(细节在「this 指向」一节展开)。但它不能作为构造函数,也没有 arguments 对象。

本节要点单参省括号、单句省 return;返回对象要包圆括号;箭头函数没有自己的 this;不能当构造函数用。
JavaScript
// 箭头函数的简写层次
const add = (a, b) => a + b;     // 多参数
const square = x => x * x;       // 单参数可省括号
const hello = () => '你好';      // 无参数
console.log(add(1, 2), square(3), hello());

// 配合数组方法非常简洁
const nums = [1, 2, 3, 4];
console.log(nums.map(n => n * 2));
console.log(nums.filter(n => n > 2));

// 多行逻辑要写 {} 和 return
const classify = (score) => {
  if (score >= 60) return '及格';
  return '不及格';
};
console.log(classify(75));

// 返回对象字面量:要加圆括号
const makeUser = (name) => ({ name: name, age: 18 });
console.log(makeUser('小明'));

// 箭头函数没有自己的 this(详见 this 一节)
const timer = {
  seconds: 0,
  start() {
    setInterval(() => {
      this.seconds++;      // 沿用 start 的 this,指向 timer
      console.log('经过秒数:' + this.seconds);
    }, 1000);
  },
};
// timer.start();  取消注释观察效果