官术网_书友最值得收藏!

Arrow functions

Arrow functions allow you to shorten function declarations, from function() {} to simply () => {}. Indeed, you can replace a line like this:

SomeEmitter.on('message', function(message) { console.log(message) });

To:

SomeEmitter.on('message', message => console.log(message));

Here, we lose both the brackets and curly braces, and the tighter code works as expected. 

Another important feature of arrow functions is they are not assigned their own this—arrow functions inherit this from the call site. For example, the following code does not work:

function Counter() {
this.count = 0;

setInterval(function() {
console.log(this.count++);
}, 1000);
}

new Counter();

The function within setInterval is being called in the context of setInterval, rather than the Counter object, so this does not have any reference to count. That is, at the function call site, this is a Timeout object, which you can check yourself by adding console.log(this) to the prior code.

With arrow functions, this is assigned at the point of definition. Fixing the code is easy:

setInterval(() => { // arrow function to the rescue!
console.log(this);
console.log(this.count++);
}, 1000);
// Counter { count: 0 }
// 0
// Counter { count: 1 }
// 1
// ...
主站蜘蛛池模板: 蕉岭县| 高青县| 上虞市| 孟津县| 临沂市| 会同县| 澄江县| 四平市| 宁国市| 濮阳县| 独山县| 南城县| 安阳县| 桓台县| 宜阳县| 民县| 洮南市| 浙江省| 伊吾县| 兴隆县| 新竹市| 册亨县| 滁州市| 昌黎县| 龙里县| 滨海县| 唐山市| 红原县| 义乌市| 资源县| 汾阳市| 葫芦岛市| 叙永县| 老河口市| 郎溪县| 安化县| 罗源县| 古交市| 红安县| 宣武区| 乌鲁木齐市|