2016-07-27 48 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]