2016-07-27 39 views
1

我正在閱讀annotated source for the Parsley javascript library,我一直看到我不完全明白的註釋。谷歌搜索並沒有真正的幫助,因爲谷歌忽略了「()=>」或「=>」作爲有用的搜索條件。Javascript notation:()=> {return 5; }

下面是一個例子:

if (event) { 
     this.submitEvent = $.extend({}, event, {preventDefault:() => { 
     ParsleyUtils.warnOnce("Using `this.submitEvent.preventDefault()` is deprecated; instead, call `this.validationResult = false`"); 
     this.validationResult = false; 
     }}); 
    } 

我能猜到發生了什麼,但我不明白的語法或函數/λ聲明或圖案的名稱。

函數聲明的模式或風格的名稱是什麼?它的目的是什麼?

+0

它被稱爲「箭頭函數語法」 –

+0

當搜索「javascript =>」的stackoverflow時,沒有結果與答案匹配。地獄上週我GOOGLE了「當時承諾」嘗試學習jQuery的延遲函數調用,也找不到任何東西。 – Kieveli

+0

'jquery推遲時'或'jquery推遲然後'或'jquery承諾然後呢?'當時承諾'是非常通用的... – nils

回答

4

這些被稱爲arrow functions,這基本上是一種ES6方法,以一種新的方式利用功能。有關怎麼回事一些簡單的背景,MDN解釋了主意,因爲這樣

兩個因素影響引進箭頭功能:更短的功能和詞彙這一點。

試試下面這個例子......

var self = this; 
setInterval(function growUp() { 
    // The callback refers to the `self` variable of which 
    // the value is the expected object. 
    self.age++; 
}, 1000); 

箭頭語法變得

// `this` here is the same as `this` in the setInterval 
setInterval(() => { 
    this.age++; // `this` properly refers to this in the outer scope 
}, 1000); 

所以你的榜樣, 「傳統」 的表示可以像這樣...

var self = this; 
if (event) { 
    self.submitEvent = $.extend({}, event, { preventDefault: function() { 
    // [...] 
    self.validationResult = false; 
    }}); 
} 

箭頭函數的另一大用處是針對一個li ners

[1,2,3,4].map(num => num * 2); // [2,4,6,8]