JavaScript 中,函數能夠用箭頭語法(」=>」)定義,有時候也叫「lambda表達式」。這種語法主要意圖是定義輕量級的內聯回調函數。例如:php
// Arrow function: [5, 8, 9].map(item => item + 1); // -> [6, 9, 10] // Classic function equivalent: [5, 8, 9].map(function(item) { return item + 1; }); // -> [6, 9, 10]
當箭頭函數有一個參數時,參數兩邊的括號是無關緊要的,可是仍是有括號看起來看清楚。web
const foo = bar => bar + 1; const bar = (baz) => baz + 1;
箭頭函數不帶參數時,必需要用括號,好比:express
const foo = () => "foo";
若是函數體不是隻一行,應該用花括號,並顯式地返回(若是須要返回值)。函數
const foo = bar => { const baz = 5; return bar + baz; }; foo(1); // -> 6
箭頭函數不會暴露 argument 對象,因此,argument 將簡單地指向當前scope內的一個變量。ui
arguments object 是全部函數中的一個本地變量。你能夠經過 arguments 對象引用函數的入參。這個對象包含傳給這個函數的每一個入參的入口,索引從0開始,例如:
arguments[0]
arguments[1]
arguments[2]this
const arguments = [true]; const foo = x => console.log(arguments[0]); foo(false); // -> true
基於此,箭頭函數也不知道它的調用者。
當缺乏arguments object時,可能會有所限制(極少數狀況),其他的參數通常能夠作爲替代。spa
const arguments = [true]; const foo = (...arguments) => console.log(arguments[0]); foo(false); // -> false
箭頭函數是 lexically scoped,這意味着其 this 綁定到了附近scope的上下文。也就是說,無論this指向什麼,均可以用一個箭頭函數保存。code
看下面的例子, Cow 類有一個方法在1秒後輸出sound。regexp
class Cow { constructor() { this.sound = "moo"; } makeSoundLater() { setTimeout(() => { console.log(this.sound); }, 1000); } } var myCow = new Cow(); var yourCow = new Cow(); yourCow.sound = "moooooo"; myCow.makeSoundLater(); yourCow.makeSoundLater();
在 makeSoundLater() 方法中,this 指向當前 Cow 對象的實例。因此在這個例子中當咱們調用 myCow.makeSoundLater(), this 指向 myCow。而後,經過使用箭頭函數,咱們保存了 this,這樣咱們就能夠在須要時引用 this.sound 了。將會輸出 「moo」,而不是yourCow.makeSoundLater()輸出的「moooooo」。對象
箭頭函數能夠經過省略掉小括號作到隱式返回值。
const foo = x => x + 1; foo(1); // -> 2
當使用隱式返回時,Object Literal 必須用花括號括起來。
Object Literal 是用花括號括起來的,分號隔開的 k-v 對象列表。
const foo = () => { bar: 1 } // foo() returns undefined const foo = () => ({ bar: 1 }) // foo() returns {bar: 1}
const foo = x => { return x + 1; } foo(1); // -> 2
x => y // Implicit return x => { return y } // Explicit return (x, y, z) => { ... } // Multiple arguments (() => { ... })() // Immediately-invoked function expression