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

IT技术 javascript ecmascript-6 arrow-functions
2021-01-24 03:22:51

我正在阅读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,如果它有任何不同,怎么会这样?

2个回答

这是 ES6 的新箭头语法。它的区别在于this根据调用上下文(传统语义)function获取 a的处理,但箭头函数保留定义上下文的thisthis

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

Mozilla 兼容表似乎不经常更新。查看我们的表格以获取最新支持 — kangax.github.io/compat-table/es6/#arrow_functions
2021-03-24 03:22:51
2021-04-13 03:22:51

ECMAScript 6arrow function引入了,箭头(=>)部分的arrow function语法。

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