箭头函数 #

一、箭头函数概述 #

箭头函数(Arrow Function)是ES6引入的一种简洁的函数语法,它具有更短的语法和词法作用域的this绑定。

二、基本语法 #

2.1 完整语法 #

typescript
const functionName = (parameters): returnType => {
  // 函数体
  return value;
};

2.2 基本示例 #

typescript
const add = (a: number, b: number): number => {
  return a + b;
};

console.log(add(1, 2)); // 3

2.3 省略花括号(单表达式) #

当函数体只有一个表达式时,可以省略花括号和return:

typescript
const add = (a: number, b: number): number => a + b;

console.log(add(1, 2)); // 3

2.4 单参数省略括号 #

当只有一个参数时,可以省略参数括号:

typescript
const double = (n: number): number => n * 2;

console.log(double(5)); // 10

2.5 无参数 #

typescript
const getTimestamp = (): number => Date.now();

console.log(getTimestamp());

三、语法变体 #

3.1 返回对象字面量 #

返回对象需要用括号包裹:

typescript
// 错误:会被解析为代码块
// const createUser = (name: string) => { name };

// 正确:用括号包裹
const createUser = (name: string) => ({ name });

console.log(createUser("Alice")); // { name: "Alice" }

3.2 多行函数体 #

typescript
const calculate = (a: number, b: number): number => {
  const sum = a + b;
  const product = a * b;
  return sum + product;
};

console.log(calculate(2, 3)); // 11

3.3 解构参数 #

typescript
interface Point {
  x: number;
  y: number;
}

const distance = ({ x, y }: Point): number => Math.sqrt(x * x + y * y);

console.log(distance({ x: 3, y: 4 })); // 5

3.4 默认参数 #

typescript
const greet = (name: string, greeting: string = "Hello"): string => 
  `${greeting}, ${name}!`;

console.log(greet("Alice")); // Hello, Alice!
console.log(greet("Bob", "Hi")); // Hi, Bob!

3.5 剩余参数 #

typescript
const sum = (...numbers: number[]): number => 
  numbers.reduce((acc, n) => acc + n, 0);

console.log(sum(1, 2, 3, 4, 5)); // 15

四、this绑定 #

4.1 词法this #

箭头函数没有自己的this,它继承外层作用域的this:

typescript
const obj = {
  name: "Alice",
  
  // 普通函数:this指向调用者
  greetRegular: function() {
    console.log(`Hello, ${this.name}`);
  },
  
  // 箭头函数:this继承外层
  greetArrow: () => {
    console.log(`Hello, ${this?.name}`);
  }
};

obj.greetRegular(); // Hello, Alice
obj.greetArrow(); // Hello, undefined(this不是obj)

4.2 回调中的this #

typescript
class Timer {
  seconds = 0;
  
  // 使用普通函数,需要绑定this
  startRegular() {
    setInterval(function() {
      // this.seconds++; // 错误:this不是Timer实例
    }, 1000);
  }
  
  // 使用箭头函数,自动绑定this
  startArrow() {
    setInterval(() => {
      this.seconds++;
      console.log(this.seconds);
    }, 1000);
  }
}

4.3 事件处理器 #

typescript
class Button {
  constructor(private label: string) {}
  
  // 普通函数需要bind
  handleClickRegular() {
    console.log(`Clicked: ${this.label}`);
  }
  
  // 箭头函数自动绑定
  handleClick = () => {
    console.log(`Clicked: ${this.label}`);
  }
}

4.4 类方法 #

typescript
class Counter {
  count = 0;
  
  // 方法:每次调用创建新函数
  increment() {
    this.count++;
  }
  
  // 箭头函数属性:实例间共享同一个函数引用
  decrement = () => {
    this.count--;
  }
}

五、箭头函数vs普通函数 #

5.1 this绑定 #

typescript
const obj = {
  value: 42,
  
  regular: function() {
    return this.value; // 动态this
  },
  
  arrow: () => {
    return (this as any)?.value; // 词法this
  }
};

console.log(obj.regular()); // 42
console.log(obj.arrow()); // undefined

5.2 arguments对象 #

箭头函数没有arguments对象:

typescript
// 普通函数
function regular() {
  console.log(arguments);
}
regular(1, 2, 3); // Arguments(3) [1, 2, 3]

// 箭头函数
const arrow = () => {
  // console.log(arguments); // 错误:arguments未定义
  console.log("使用剩余参数代替");
};

5.3 构造函数 #

箭头函数不能作为构造函数:

typescript
// 普通函数
function Person(name: string) {
  this.name = name;
}
const alice = new (Person as any)("Alice"); // 正确

// 箭头函数
const PersonArrow = (name: string) => {
  (this as any).name = name;
};
// const bob = new PersonArrow("Bob"); // 错误

5.4 prototype属性 #

箭头函数没有prototype属性:

typescript
function regular() {}
console.log(regular.prototype); // { constructor: f }

const arrow = () => {};
console.log(arrow.prototype); // undefined

5.5 call/apply/bind #

typescript
const obj = { value: 42 };

// 普通函数
function regular() {
  return this.value;
}
console.log(regular.call(obj)); // 42

// 箭头函数
const arrow = () => (this as any)?.value;
console.log(arrow.call(obj)); // undefined(this不受影响)

六、使用场景 #

6.1 数组方法 #

typescript
const numbers = [1, 2, 3, 4, 5];

// map
const doubled = numbers.map(n => n * 2);
console.log(doubled); // [2, 4, 6, 8, 10]

// filter
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // [2, 4]

// reduce
const sum = numbers.reduce((acc, n) => acc + n, 0);
console.log(sum); // 15

// sort
const sorted = [...numbers].sort((a, b) => b - a);
console.log(sorted); // [5, 4, 3, 2, 1]

6.2 Promise链 #

typescript
fetch("https://api.example.com/data")
  .then(response => response.json())
  .then(data => data.results)
  .then(results => results.map((r: any) => r.name))
  .then(names => console.log(names))
  .catch(error => console.error(error));

6.3 async/await #

typescript
const fetchData = async (url: string) => {
  const response = await fetch(url);
  return response.json();
};

const processData = async (data: any) => {
  return data.map((item: any) => item.value);
};

6.4 事件处理器 #

typescript
document.addEventListener("click", (event) => {
  console.log(`Clicked at ${event.clientX}, ${event.clientY}`);
});

setTimeout(() => {
  console.log("Delayed execution");
}, 1000);

6.5 对象方法(需注意) #

typescript
const calculator = {
  value: 0,
  
  // 不推荐:this问题
  add: (n: number) => {
    // calculator.value += n; // 需要直接引用对象
  },
  
  // 推荐:使用普通方法
  subtract(n: number) {
    this.value -= n;
  }
};

七、实际应用 #

7.1 函数式编程 #

typescript
const pipe = <T>(...fns: Array<(arg: T) => T>) => 
  (x: T) => fns.reduce((v, f) => f(v), x);

const trim = (s: string) => s.trim();
const toLower = (s: string) => s.toLowerCase();
const split = (s: string) => s.split("");

const process = pipe(trim, toLower, split);
console.log(process("  HELLO  ")); // ["h", "e", "l", "l", "o"]

7.2 柯里化 #

typescript
const curry = <T, U, V>(fn: (a: T, b: U) => V) => 
  (a: T) => (b: U) => fn(a, b);

const add = (a: number, b: number) => a + b;
const curriedAdd = curry(add);

const add5 = curriedAdd(5);
console.log(add5(3)); // 8

7.3 工厂函数 #

typescript
const createValidator = (rules: Array<(value: any) => string | null>) => 
  (value: any) => rules.map(rule => rule(value)).filter(Boolean);

const validateName = createValidator([
  (v) => !v ? "必填" : null,
  (v) => v.length < 3 ? "至少3个字符" : null,
]);

console.log(validateName("")); // ["必填"]
console.log(validateName("ab")); // ["至少3个字符"]
console.log(validateName("Alice")); // []

八、最佳实践 #

8.1 选择正确的函数类型 #

typescript
// 对象方法:使用普通方法
const obj = {
  name: "Alice",
  greet() {
    console.log(`Hello, ${this.name}`);
  }
};

// 回调函数:使用箭头函数
const numbers = [1, 2, 3];
numbers.forEach(n => console.log(n));

// 类方法需要绑定this:使用箭头函数属性
class Component {
  handleClick = () => {
    console.log(this);
  };
}

8.2 保持简洁 #

typescript
// 推荐:简洁明了
const double = (n: number) => n * 2;
const isEven = (n: number) => n % 2 === 0;

// 不推荐:过度简化导致可读性差
// const f=x=>x*2;

8.3 适当的换行 #

typescript
// 复杂表达式可以换行
const process = (data: { items: { value: number }[] }) =>
  data.items
    .filter(item => item.value > 0)
    .map(item => item.value * 2)
    .reduce((sum, value) => sum + value, 0);

九、总结 #

本章学习了:

  • 箭头函数的基本语法
  • 各种语法变体
  • this绑定的区别
  • 箭头函数与普通函数的区别
  • 使用场景
  • 最佳实践

下一章,我们将学习函数参数。

最后更新:2026-03-28