Skip to content

Arrow 函数

Concise 函数语法使用 implicit 返回 and lexical 这个 binding for 回调.

你将学到

  • Arrow 函数语法: 单个 and multi-表达式 bodies
  • Implicit 返回不使用返回 keyword
  • 为什么 arrow 函数有 否 own 这个, 实参, or 原型
  • 当 arrow 函数是 ideal (回调, transformations)
  • 当到 avoid arrow 函数 (对象方法, constructors)

概念讲解

Concise Syntax

Arrow functions, introduced in ES6, offer a shorter way to write function expressions. A simple transformation like 函数(x) { 返回 x * 2; } becomes (x) => x * 2. When the body is a single expression, the 返回 keyword and braces are optional — the expression is returned implicitly. For a single parameter, the parentheses around the parameter can also be dropped: x => x * 2.

Implicit Return

The implicit-return form is perfect for short callbacks passed to 映射, 筛选, and 排序. It keeps code horizontal and readable. When you need multiple statements, use a block body with braces and an explicit 返回. Returning an object literal implicitly requires parentheses around it, so the braces are not mistaken for a function block: () => ({ 键: 值 }).

Lexical this

The most important semantic difference is that arrow functions do not have their own 这个. They inherit 这个 from the enclosing scope (lexical binding). This eliminates the old pattern of var self = 这个 or .bind(这个) in callbacks. Inside an arrow function, 这个 is whatever it was where the arrow was defined.

No arguments, No prototype

Arrow functions also lack their own 实参 object and cannot be used as constructors with 新. Use rest parameters (...args) instead of 实参. Attempting 新 (() => {}) throws a TypeError.

When to Avoid Them

Because they lack their own 这个, arrow functions are a poor choice for object methods that need to access the object via 这个, and for prototype methods on classes. Use regular function expressions or method shorthand in those cases. Arrow functions shine as callbacks, event handlers bound to a component, and short pure transformations.

示例代码

              // Concise syntax with implicit return
const square = (n) => n * n;
const cube = (n) => n * n * n;
console.log(square(5), cube(3)); // 25 27

// Implicit return of an object — wrap in parentheses
const makeUser = (name, age) => ({ name, age, active: true });
console.log(makeUser("Ada", 36));

// Arrow functions as callbacks — no .bind(this) needed
class Counter {
  constructor() {
    this.count = 0;
  }
  start() {
    // 'this' inside the arrow refers to the Counter instance
    setInterval(() => {
      this.count++;
      console.log("tick", this.count);
    }, 1000);
  }
}

// Sorting with a concise comparator
const nums = [3, 1, 4, 1, 5, 9, 2, 6];
nums.sort((a, b) => a - b);
console.log("Sorted:", nums);

// Block body when you need multiple statements
const process = (items) => {
  const filtered = items.filter((x) => x != null);
  const total = filtered.reduce((sum, x) => sum + x, 0);
  return { count: filtered.length, total };
};
console.log(process([1, null, 2, 3, null]));
            

Shows implicit 返回, returning 对象 literal 使用 parentheses, lexical 这个 in 类回调 (否 bind 需要), concise 排序 comparator, and 块请求体使用多个语句.

动手试一试

  • Math Evaluator

    Arrow 函数经常 wrap math logic — evaluate 表达式 live.

  • Regex Tester

    Arrow 函数是 通常 used as regex 测试回调.

常见错误

错误写法

Using arrow 函数 as 对象方法 and losing 这个

正确做法

Arrow 函数 inherit 这个从 surrounding 作用域, 不对象. For 方法那个需要这个, use 方法 shorthand ({ 方法() { ... } }) or regular 函数表达式.

错误写法

Forgetting parentheses 当 implicitly returning 对象 literal

正确做法

() => { 键: 值 } 是 parsed as 块请求体, 不对象. 编写 () => ({ 键: 值 }) 所以 braces 是 treated as 对象 literal.

相关速查表

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误