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

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
// ...
主站蜘蛛池模板: 贺州市| 大田县| 喀喇| 喀喇沁旗| 乳源| 平塘县| 富宁县| 南溪县| 巴东县| 马边| 广南县| 含山县| 手机| 堆龙德庆县| 甘肃省| 崇仁县| 石屏县| 玉屏| 东乌珠穆沁旗| 虹口区| 湛江市| 道真| 徐水县| 常德市| 汉阴县| 瑞丽市| 铜川市| 安多县| 弥渡县| 嵩明县| 宜良县| 新蔡县| 水城县| 云南省| 垫江县| 乐都县| 阿拉尔市| 谷城县| 舒城县| 密云县| 赣榆县|