- Mastering Node.js(Second Edition)
- Sandro Pasquali Kevin Faaborg
- 201字
- 2021-07-02 19:28:40
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
// ...
- 連接未來:從古登堡到谷歌的網絡革命
- 物聯網識別技術
- Building Django 2.0 Web Applications
- 電子政務效益的經濟分析與評價
- 新一代物聯網架構技術:分層算力網絡
- 互聯網安全的40個智慧洞見:2015年中國互聯網安全大會文集
- 2018網信發展報告
- CCNP TSHOOT(642-832)認證考試指南
- Kong網關:入門、實戰與進階
- SAE原理與網絡規劃
- 語音信號處理及Blackfin DSP實現
- bash網絡安全運維
- Guide to NoSQL with Azure Cosmos DB
- 移動互聯網環境下的核心網剖析及演進
- React Design Patterns and Best Practices(Second Edition)