箭头函数 '() => {}' 在 Javascript 中是什么意思?

What does arrow function '() => {}' mean in Javascript?

本文关键字:Javascript 是什么 意思 函数      更新时间:2023-09-26

我正在阅读ScrollListView的源代码,在几个地方我看到了() => {}的使用。

如第25行,

this.cellReorderThreshold = () => {
    var ratio = (this.CELLHEIGHT*this.cellsWithinViewportCount)/4;
    return ratio < this.CELLHEIGHT ? 0 : ratio;
};

31号线,

this.container.addEventListener('scroll', () => this.onScroll(), false);

第 88 行。

resizeTimer = setTimeout(() => {
    this.containerHeight = this.container.offsetHeight;
}, 250);

这是function的简写吗,如果它有任何不同,如何?

这是 ES6 的新箭头语法。它的不同之处在于this的处理:function根据调用上下文(传统语义)获得this,但箭头函数保持定义上下文的this

见 http://tc39wiki.calculist.org/es6/arrow-functions/

ECMAScript 6 arrow function介绍,Arrow (=>) arrow function 语法的一部分。

箭头函数的工作方式与传统的 JavaScript 函数不同。我发现这篇文章解释了与传统函数的不同之处:http://www.nczonline.net/blog/2013/09/10/understanding-ecmascript-6-arrow-functions/