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/

相关文章:

javascript - 装载机不工作

javascript - 使用 'as'会产生两个编译错误

reactjs - ES6 React 和 ESLint 支持

javascript - 如何在 ES6 中销毁嵌套在一个对象中的两个变量

javascript - 如何使用reduce从数组中删除元素?

Javascript 向下滚动 vh

javascript - Node.js 中可继承的静态方法吗?

javascript - 评论在 JS 中是如何分类的?

c# - VB.NET 中的“Null-Safe”点符号……或者它是否存在于任何语言中? 'safe dereferencing operator' 或等效使用 LINQ?

c# - C# 中的接口(interface)实现语法选项