箭头函数(Arrow Functions)

ES6 引入的简化函数语法,并改变 this 绑定行为。


📚 基本语法

基本形式

// 传统函数
function add(a, b) {
  return a + b;
}
 
// 箭头函数
const add = (a, b) => {
  return a + b;
};
 
// 简化形式(单表达式)
const add = (a, b) => a + b;

参数

// 单个参数(可省略括号)
const square = x => x * x;
 
// 多个参数(必须括号)
const add = (a, b) => a + b;
 
// 无参数(必须括号)
const greet = () => 'Hello';

函数体

// 单表达式(自动返回)
const double = x => x * 2;
 
// 多语句(需要大括号和 return)
const process = x => {
  const doubled = x * 2;
  return doubled + 1;
};

🎯 特性

1. 不绑定 this

箭头函数不绑定自己的 this,继承外层作用域的 this

const person = {
  name: 'Alice',
  greet: function() {
    setTimeout(() => {
      console.log(`Hello, I'm ${this.name}`); // this 指向 person
    }, 100);
  }
};
 
person.greet(); // "Hello, I'm Alice"

对比普通函数:

const person = {
  name: 'Alice',
  greet: function() {
    setTimeout(function() {
      console.log(`Hello, I'm ${this.name}`); // this 指向 window
    }, 100);
  }
};
 
person.greet(); // "Hello, I'm undefined"

2. 不绑定 arguments

function traditional() {
  console.log(arguments); // 类数组对象
}
 
const arrow = () => {
  console.log(arguments); // ReferenceError
};
 
// 使用剩余参数
const arrow = (...args) => {
  console.log(args); // 数组
};

3. 不能作为构造函数

// ❌ 错误:箭头函数不能作为构造函数
const Person = (name) => {
  this.name = name;
};
const person = new Person('Alice'); // TypeError
 
// ✅ 正确:使用普通函数
function Person(name) {
  this.name = name;
}
const person = new Person('Alice');

4. 没有 prototype

const arrow = () => {};
console.log(arrow.prototype); // undefined
 
function traditional() {}
console.log(traditional.prototype); // { constructor: f }

💡 使用场景

1. 数组方法

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(n => n * 2);
const evens = numbers.filter(n => n % 2 === 0);
const sum = numbers.reduce((acc, n) => acc + n, 0);

2. 回调函数

// 事件处理
button.addEventListener('click', () => {
  console.log('Button clicked');
});
 
// Promise
fetch('/api/data')
  .then(response => response.json())
  .then(data => console.log(data));

3. 保持 this 上下文

class Counter {
  constructor() {
    this.count = 0;
  }
  
  increment() {
    // 箭头函数保持 this
    setInterval(() => {
      this.count++;
      console.log(this.count);
    }, 1000);
  }
}

4. 函数式编程

const compose = (...fns) => x => fns.reduceRight((acc, fn) => fn(acc), x);
const pipe = (...fns) => x => fns.reduce((acc, fn) => fn(acc), x);

⚠️ 注意事项

1. 不适合作为对象方法

const obj = {
  name: 'Alice',
  greet: () => {
    console.log(`Hello, I'm ${this.name}`); // this 指向外层
  }
};
 
obj.greet(); // "Hello, I'm undefined"

2. 不能使用 call/apply/bind 改变 this

const arrow = () => console.log(this);
const obj = { name: 'Alice' };
 
arrow.call(obj); // this 仍然是外层作用域的 this

3. 不适合需要动态 this 的场景

// ❌ 不适合:需要动态 this
const button = document.querySelector('button');
button.addEventListener('click', () => {
  // this 不是 button
  console.log(this); // window
});
 
// ✅ 适合:使用普通函数
button.addEventListener('click', function() {
  console.log(this); // button
});

🔄 与传统函数对比

特性箭头函数传统函数
this 绑定继承外层动态绑定
arguments
构造函数不能
prototype
语法简洁完整

🔗 相关链接


参考


javascript 箭头函数 arrow-function 函数式编程