什么是箭头函数 '() =>{}' 在 Javascript 中是什么意思?
问题描述:
我正在阅读 ScrollListView 的源代码和几个我看到使用 () => 的地方{}
.
I was reading the source for ScrollListView and in several places I see the use of () => {}
.
如第 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
的简写吗?如果有任何不同,那是什么?
Is this a shorthand for function
and if it differs in any way, how so?
答
这是 ES6 的新箭头语法.它的区别在于对this
的处理:function
根据调用上下文(传统语义)得到一个this
,但是箭头函数保留了定义上下文的this
.
This is the new arrow syntax of ES6. It differs by the treatment of this
: function
gets a this
according to the calling context (traditional semantics), but the arrow functions keep the this
of the context of definition.