- Mastering JavaScript Functional Programming
- Federico Kereki
- 181字
- 2021-07-02 22:41:07
Closures
Closures are a way to implement data hiding (with private variables), which leads to modules and other nice features. The key concept is that when you define a function, it can refer to not only its own local variables, but also to everything outside of the context of the function:
function newCounter() {
let count = 0;
return function() {
count++;
return count;
};
}
const nc = newCounter();
console.log(nc()); // 1
console.log(nc()); // 2
console.log(nc()); // 3
Even after newCounter exits, the inner function still has access to count, but that variable is not accessible to any other parts of your code.
This isn't a very good example of FP -- a function (nc(), in this case) isn't expected to return different results when called with the same parameters!
We'll find several uses for closures: among others, memoization (see chapter 4, Behaving Properly - Pure Functions, and chapter 6, Producing Functions - Higher-Order Functions) and the module pattern (see chapter 3, Starting Out with Functions - A Core Concept, and chapter 11, Implementing Design Patterns - The Functional Way).
- Learning Neo4j
- LabVIEW 2018 虛擬儀器程序設(shè)計(jì)
- Spring Boot開(kāi)發(fā)與測(cè)試實(shí)戰(zhàn)
- UML和模式應(yīng)用(原書(shū)第3版)
- Network Automation Cookbook
- Android 7編程入門(mén)經(jīng)典:使用Android Studio 2(第4版)
- HTML5從入門(mén)到精通 (第2版)
- C++新經(jīng)典
- Oracle 18c 必須掌握的新特性:管理與實(shí)戰(zhàn)
- 微服務(wù)從小白到專(zhuān)家:Spring Cloud和Kubernetes實(shí)戰(zhàn)
- Mastering React
- PrimeFaces Blueprints
- Java Web應(yīng)用開(kāi)發(fā)給力起飛
- AutoCAD基礎(chǔ)教程
- SQL Server實(shí)例教程(2008版)