我正在通读 annotated source for the Parsley javascript library ,而且我不断看到我不完全理解的符号。谷歌搜索并没有真正帮助,因为谷歌忽略了“() =>”或“=>”作为有用的搜索词。
这是一个例子:
if (event) {
this.submitEvent = $.extend({}, event, {preventDefault: () => {
ParsleyUtils.warnOnce("Using `this.submitEvent.preventDefault()` is deprecated; instead, call `this.validationResult = false`");
this.validationResult = false;
}});
}
我能猜到发生了什么,但我不明白函数/lambda 声明或模式的语法或名称。
函数声明的模式或样式的名称是什么?它的用途是什么?
这些被称为 arrow functions ,这基本上是一种以稍微新的方式利用函数的 ES6 方法。有关发生的事情的一些简单背景,MDN解释这个想法
Two factors influenced the introduction of arrow functions: shorter functions and lexical this.
看看这个例子...
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;
}});
}
箭头函数的另一个重要用途是单行
[1,2,3,4].map(num => num * 2); // [2,4,6,8]