Arrow functions表達式相比函數表達式有更短的語法,沒有本身的this、argument、super或者new.target。express
基礎語法:函數
(param1, param2, …, paramN) => { statements }ui
(param1, param2, …, paramN) => expressionthis
// equivalent to: => { return expression; }spa
// Parentheses are optional when there's only one parameter name:rest
(singleParam) => { statements }ci
singleParam => { statements }get
// The parameter list for a function with no parameters should be written with a pair of parentheses.it
() => { statements }io
高級語法:
// Parenthesize the body of function to return an object literal expression:
params => ({foo: bar})
// Rest parameters and default parameters are supported
(param1, param2, ...rest) => { statements }
(param1 = defaultValue1, param2, …, paramN = defaultValueN) => {
statements }
// Destructuring within the parameter list is also supported
var f = ([a, b] = [1, 2], {x: c} = {x: a + b}) => a + b + c;
f(); // 6
箭頭函數表達式最適合非方法函數
Eg:
'use strict';
var obj = {
i: 10,
b: () => console.log(this.i, this),
c: function() {
console.log(this.i, this);
}
}
obj.b(); // prints undefined, Window {...} (or the global object)
obj.c(); // prints 10, Object {...}
箭頭功能能夠具備「簡潔的身體」或一般的「塊體」。
在簡潔的主體中,只指定了一個表達式,該表達式成爲顯式返回值。在塊體中,您必須使用顯式return語句。
Eg:
var func = x => x * x;
// concise body syntax, implied "return"
var func = (x, y) => { return x + y; };
// with block body, explicit "return" needed
雖然箭頭函數中的箭頭不是運算符,但箭頭函數具備特殊的解析規則,與常規函數相比,它們與運算符優先級的交互方式不一樣。
let callback;
callback = callback || function() {}; // ok
callback = callback || () => {};
// SyntaxError: invalid arrow-function arguments
callback = callback || (() => {}); // ok