- 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).
- 極簡算法史:從數學到機器的故事
- AngularJS入門與進階
- WebAssembly實戰
- Cross-platform Desktop Application Development:Electron,Node,NW.js,and React
- 網頁設計與制作教程(HTML+CSS+JavaScript)(第2版)
- 精通Scrapy網絡爬蟲
- JSP開發案例教程
- Advanced Oracle PL/SQL Developer's Guide(Second Edition)
- Unity Game Development Scripting
- Python Interviews
- Python語言科研繪圖與學術圖表繪制從入門到精通
- ActionScript 3.0從入門到精通(視頻實戰版)
- Android高級開發實戰:UI、NDK與安全
- ASP.NET本質論
- Python High Performance(Second Edition)