Javascript 符号 : () => { return 5; }

标签 javascript syntax ecmascript-6

<分区>

我正在通读 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]

关于Javascript 符号 : () => { return 5; },我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38617118/

相关文章:

r - R 中的符号::: 是什么意思

javascript - MochaJS setTimeout ES6

ecmascript-6 - JSX 中的虚拟 DOM 操作 (React)

javascript - 在 div 中显示 URL 的内容

JavaScript 跨浏览器点击 HTML DOM 元素

ruby - 是否有任何你避免使用的 Ruby 语言特性?

javascript - Ext JS - 如何理解语法

javascript - 将箭头与 slider 功能分开

Javascript 函数在两个特定值之间反转

javascript - Typescript 中的抽象内部类