箭头函数表达式
箭头函数表达式是传统 函数表达式 的紧凑替代品,具有一些语义差异和使用方面的故意限制:
¥An arrow function expression is a compact alternative to a traditional function expression, with some semantic differences and deliberate limitations in usage:
- 箭头函数没有自己的 bindings 到
this
、arguments
或super
,并且不应用作 methods。 - 箭头函数不能用作 constructors。用
new
调用它们会抛出TypeError
。他们也无权访问new.target
关键字。 - 箭头函数不能在其函数体内使用
yield
,也不能创建为生成器函数。
Try it
语法
¥Syntax
() => expression
param => expression
(param) => expression
(param1, paramN) => expression
() => {
statements
}
param => {
statements
}
(param1, paramN) => {
statements
}
支持参数内的 其余参数、默认参数 和 destructuring,并且始终需要括号:
¥Rest parameters, default parameters, and destructuring within params are supported, and always require parentheses:
(a, b, ...r) => expression
(a = 400, b = 20, c) => expression
([a, b] = [10, 20]) => expression
({ a, b } = { a: 10, b: 20 }) => expression
通过在表达式前加上 async
关键字前缀,箭头函数可以是 async
。
¥Arrow functions can be async
by prefixing the expression with the async
keyword.
async param => expression
async (param1, param2, ...paramN) => {
statements
}
描述
¥Description
让我们逐步将传统的匿名函数分解为最简单的箭头函数。沿途的每一步都是一个有效的箭头函数。
¥Let's decompose a traditional anonymous function down to the simplest arrow function step-by-step. Each step along the way is a valid arrow function.
注意:传统函数表达式和箭头函数除了语法之外还有更多差异。我们将在接下来的几小节中更详细地介绍他们的行为差异。
¥Note: Traditional function expressions and arrow functions have more differences than their syntax. We will introduce their behavior differences in more detail in the next few subsections.
// Traditional anonymous function
(function (a) {
return a + 100;
});
// 1. Remove the word "function" and place arrow between the argument and opening body brace
(a) => {
return a + 100;
};
// 2. Remove the body braces and word "return" — the return is implied.
(a) => a + 100;
// 3. Remove the parameter parentheses
a => a + 100;
在上面的示例中,参数周围的括号和函数体周围的大括号都可以省略。但是,只有在某些情况下才能省略它们。
¥In the example above, both the parentheses around the parameter and the braces around the function body may be omitted. However, they can only be omitted in certain cases.
仅当函数具有单个简单参数时才可以省略括号。如果它有多个参数、没有参数或默认参数、解构参数或剩余参数,则需要在参数列表两边加上括号。
¥The parentheses can only be omitted if the function has a single simple parameter. If it has multiple parameters, no parameters, or default, destructured, or rest parameters, the parentheses around the parameter list are required.
// Traditional anonymous function
(function (a, b) {
return a + b + 100;
});
// Arrow function
(a, b) => a + b + 100;
const a = 4;
const b = 2;
// Traditional anonymous function (no parameters)
(function () {
return a + b + 100;
});
// Arrow function (no parameters)
() => a + b + 100;
仅当函数直接返回表达式时才可以省略大括号。如果主体包含语句,则括号是必需的 — return
关键字也是如此。箭头函数无法猜测你想要返回什么或何时返回。
¥The braces can only be omitted if the function directly returns an expression. If the body has statements, the braces are required — and so is the return
keyword. Arrow functions cannot guess what or when you want to return.
// Traditional anonymous function
(function (a, b) {
const chuck = 42;
return a + b + chuck;
});
// Arrow function
(a, b) => {
const chuck = 42;
return a + b + chuck;
};
箭头函数本身并不与名称相关联。如果箭头函数需要调用自身,请改用命名函数表达式。你还可以将箭头函数分配给变量,从而允许你通过该变量引用它。
¥Arrow functions are not inherently associated with a name. If the arrow function needs to call itself, use a named function expression instead. You can also assign the arrow function to a variable, allowing you to refer to it through that variable.
// Traditional Function
function bob(a) {
return a + 100;
}
// Arrow Function
const bob2 = (a) => a + 100;
函数体
¥Function body
箭头函数可以具有表达式主体或通常的块主体。
¥Arrow functions can have either an expression body or the usual block body.
在表达式主体中,仅指定单个表达式,该表达式成为隐式返回值。在块体中,必须使用显式 return
语句。
¥In an expression body, only a single expression is specified, which becomes the implicit return value. In a block body, you must use an explicit return
statement.
const func = (x) => x * x;
// expression body syntax, implied "return"
const func2 = (x, y) => {
return x + y;
};
// with block body, explicit "return" needed
使用表达式主体语法 (params) => { object: literal }
返回对象文字无法按预期工作。
¥Returning object literals using the expression body syntax (params) => { object: literal }
does not work as expected.
const func = () => { foo: 1 };
// Calling func() returns undefined!
const func2 = () => { foo: function () {} };
// SyntaxError: function statement requires a name
const func3 = () => { foo() {} };
// SyntaxError: Unexpected token '{'
这是因为如果箭头后面的标记不是左大括号,JavaScript 只会将箭头函数视为具有表达式主体,因此大括号 ({}) 内的代码会被解析为语句序列,其中 foo
是 label,而不是 键入对象文字。
¥This is because JavaScript only sees the arrow function as having an expression body if the token following the arrow is not a left brace, so the code inside braces ({}) is parsed as a sequence of statements, where foo
is a label, not a key in an object literal.
要解决此问题,请将对象文字括在括号中:
¥To fix this, wrap the object literal in parentheses:
const func = () => ({ foo: 1 });
不能用作方法
¥Cannot be used as methods
箭头函数表达式只能用于非方法函数,因为它们没有自己的 this
。让我们看看当我们尝试将它们用作方法时会发生什么:
¥Arrow function expressions should only be used for non-method functions because they do not have their own this
. Let's see what happens when we try to use them as methods:
"use strict";
const obj = {
i: 10,
b: () => console.log(this.i, this),
c() {
console.log(this.i, this);
},
};
obj.b(); // logs undefined, Window { /* … */ } (or the global object)
obj.c(); // logs 10, Object { /* … */ }
另一个涉及 Object.defineProperty()
的例子:
¥Another example involving Object.defineProperty()
:
"use strict";
const obj = {
a: 10,
};
Object.defineProperty(obj, "b", {
get: () => {
console.log(this.a, typeof this.a, this); // undefined 'undefined' Window { /* … */ } (or the global object)
return this.a + 10; // represents global object 'Window', therefore 'this.a' returns 'undefined'
},
});
因为 class 的主体具有 this
上下文,所以箭头函数作为 类字段 靠近类的 this
上下文,并且箭头函数主体内的 this
将正确指向实例(或类本身,对于 静态字段)。但是,由于它是 closure,而不是函数自己的绑定,因此 this
的值不会根据执行上下文而改变。
¥Because a class's body has a this
context, arrow functions as class fields close over the class's this
context, and the this
inside the arrow function's body will correctly point to the instance (or the class itself, for static fields). However, because it is a closure, not the function's own binding, the value of this
will not change based on the execution context.
class C {
a = 1;
autoBoundMethod = () => {
console.log(this.a);
};
}
const c = new C();
c.autoBoundMethod(); // 1
const { autoBoundMethod } = c;
autoBoundMethod(); // 1
// If it were a normal method, it should be undefined in this case
箭头函数属性通常被称为 "自动绑定方法",因为与普通方法的等价物是:
¥Arrow function properties are often said to be "auto-bound methods", because the equivalent with normal methods is:
class C {
a = 1;
constructor() {
this.method = this.method.bind(this);
}
method() {
console.log(this.a);
}
}
注意:类字段是在实例上定义的,而不是在原型上定义的,因此每个实例创建都会创建一个新的函数引用并分配一个新的闭包,这可能会导致比正常的未绑定方法使用更多的内存。
¥Note: Class fields are defined on the instance, not on the prototype, so every instance creation would create a new function reference and allocate a new closure, potentially leading to more memory usage than a normal unbound method.
出于类似的原因,在箭头函数上调用时,call()
、apply()
和 bind()
方法没有用处,因为箭头函数根据定义箭头函数的作用域建立 this
,而 this
值不会根据函数的执行方式而改变 调用。
¥For similar reasons, the call()
, apply()
, and bind()
methods are not useful when called on arrow functions, because arrow functions establish this
based on the scope the arrow function is defined within, and the this
value does not change based on how the function is invoked.
没有参数的绑定
¥No binding of arguments
箭头函数没有自己的 arguments
对象。因此,在此示例中,arguments
是对封闭范围的参数的引用:
¥Arrow functions do not have their own arguments
object. Thus, in this example, arguments
is a reference to the arguments of the enclosing scope:
function foo(n) {
const f = () => arguments[0] + n; // foo's implicit arguments binding. arguments[0] is n
return f();
}
foo(3); // 3 + 3 = 6
注意:你不能在 严格模式 中声明名为
arguments
的变量,因此上面的代码将是语法错误。这使得arguments
的范围效应更容易理解。¥Note: You cannot declare a variable called
arguments
in strict mode, so the code above would be a syntax error. This makes the scoping effect ofarguments
much easier to comprehend.
在大多数情况下,使用 其余参数 是使用 arguments
对象的一个很好的替代方案。
¥In most cases, using rest parameters
is a good alternative to using an arguments
object.
function foo(n) {
const f = (...args) => args[0] + n;
return f(10);
}
foo(1); // 11
不能用作构造函数
¥Cannot be used as constructors
箭头函数不能用作构造函数,并且在使用 new
调用时会抛出错误。他们也没有 prototype
属性。
¥Arrow functions cannot be used as constructors and will throw an error when called with new
. They also do not have a prototype
property.
const Foo = () => {};
const foo = new Foo(); // TypeError: Foo is not a constructor
console.log("prototype" in Foo); // false
不能用作生成器
¥Cannot be used as generators
yield
关键字不能在箭头函数主体中使用(除非在进一步嵌套在箭头函数中的生成器函数中使用)。因此,箭头函数不能用作生成器。
¥The yield
keyword cannot be used in an arrow function's body (except when used within generator functions further nested within the arrow function). As a consequence, arrow functions cannot be used as generators.
箭头前换行
¥Line break before arrow
箭头函数的参数和箭头之间不能包含换行符。
¥An arrow function cannot contain a line break between its parameters and its arrow.
const func = (a, b, c)
=> 1;
// SyntaxError: Unexpected token '=>'
为了格式化,你可以在箭头后面放置换行符或在函数体周围使用圆括号/大括号,如下所示。你还可以在参数之间放置换行符。
¥For the purpose of formatting, you may put the line break after the arrow or use parentheses/braces around the function body, as shown below. You can also put line breaks between parameters.
const func = (a, b, c) =>
1;
const func2 = (a, b, c) => (
1
);
const func3 = (a, b, c) => {
return 1;
};
const func4 = (
a,
b,
c,
) => 1;
箭头的优先级
¥Precedence of arrow
尽管箭头函数中的箭头不是运算符,但箭头函数具有特殊的解析规则,与常规函数相比,它们与 运算符优先级 的交互方式不同。
¥Although the arrow in an arrow function is not an operator, arrow functions have special parsing rules that interact differently with operator precedence compared to regular functions.
let callback;
callback = callback || () => {};
// SyntaxError: invalid arrow-function arguments
由于 =>
的优先级低于大多数运算符,因此需要使用括号来避免 callback || ()
被解析为箭头函数的参数列表。
¥Because =>
has a lower precedence than most operators, parentheses are necessary to avoid callback || ()
being parsed as the arguments list of the arrow function.
callback = callback || (() => {});
示例
使用箭头函数
¥Using arrow functions
// An empty arrow function returns undefined
const empty = () => {};
(() => "foobar")();
// Returns "foobar"
// (this is an Immediately Invoked Function Expression)
const simple = (a) => (a > 15 ? 15 : a);
simple(16); // 15
simple(10); // 10
const max = (a, b) => (a > b ? a : b);
// Easy array filtering, mapping, etc.
const arr = [5, 6, 13, 0, 1, 18, 23];
const sum = arr.reduce((a, b) => a + b);
// 66
const even = arr.filter((v) => v % 2 === 0);
// [6, 0, 18]
const double = arr.map((v) => v * 2);
// [10, 12, 26, 0, 2, 36, 46]
// More concise promise chains
promise
.then((a) => {
// …
})
.then((b) => {
// …
});
// Parameterless arrow functions that are visually easier to parse
setTimeout(() => {
console.log("I happen sooner");
setTimeout(() => {
// deeper code
console.log("I happen later");
}, 1);
}, 1);
使用调用、绑定和应用
¥Using call, bind, and apply
call()
、apply()
和 bind()
方法可以按照传统函数的预期工作,因为我们为每个方法建立了范围:
¥The call()
, apply()
, and bind()
methods work as expected with traditional functions, because we establish the scope for each of the methods:
const obj = {
num: 100,
};
// Setting "num" on globalThis to show how it is NOT used.
globalThis.num = 42;
// A simple traditional function to operate on "this"
const add = function (a, b, c) {
return this.num + a + b + c;
};
console.log(add.call(obj, 1, 2, 3)); // 106
console.log(add.apply(obj, [1, 2, 3])); // 106
const boundAdd = add.bind(obj);
console.log(boundAdd(1, 2, 3)); // 106
对于箭头函数,由于我们的 add
函数本质上是在 globalThis
(全局)作用域上创建的,因此它会假设 this
是 globalThis
。
¥With arrow functions, since our add
function is essentially created on the globalThis
(global) scope, it will assume this
is the globalThis
.
const obj = {
num: 100,
};
// Setting "num" on globalThis to show how it gets picked up.
globalThis.num = 42;
// Arrow function
const add = (a, b, c) => this.num + a + b + c;
console.log(add.call(obj, 1, 2, 3)); // 48
console.log(add.apply(obj, [1, 2, 3])); // 48
const boundAdd = add.bind(obj);
console.log(boundAdd(1, 2, 3)); // 48
也许使用箭头函数的最大好处是像 setTimeout()
和 EventTarget.prototype.addEventListener()
这样的方法通常需要某种闭包、call()
、apply()
或 bind()
以确保函数在正确的范围内执行。
¥Perhaps the greatest benefit of using arrow functions is with methods like setTimeout()
and EventTarget.prototype.addEventListener()
that usually require some kind of closure, call()
, apply()
, or bind()
to ensure that the function is executed in the proper scope.
对于传统的函数表达式,这样的代码不能按预期工作:
¥With traditional function expressions, code like this does not work as expected:
const obj = {
count: 10,
doSomethingLater() {
setTimeout(function () {
// the function executes on the window scope
this.count++;
console.log(this.count);
}, 300);
},
};
obj.doSomethingLater(); // logs "NaN", because the property "count" is not in the window scope.
使用箭头函数,可以更轻松地保留 this
范围:
¥With arrow functions, the this
scope is more easily preserved:
const obj = {
count: 10,
doSomethingLater() {
// The method syntax binds "this" to the "obj" context.
setTimeout(() => {
// Since the arrow function doesn't have its own binding and
// setTimeout (as a function call) doesn't create a binding
// itself, the "obj" context of the outer method is used.
this.count++;
console.log(this.count);
}, 300);
},
};
obj.doSomethingLater(); // logs 11
规范
Specification |
---|
ECMAScript Language Specification # sec-arrow-function-definitions |
浏览器兼容性
BCD tables only load in the browser
也可以看看
¥See also
- 函数 指南
- 函数
function
function
表达- hacks.mozilla.org 上的 ES6 深入了解:箭头函数 (2015)