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

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).

主站蜘蛛池模板: 西乌珠穆沁旗| 和田市| 金寨县| 景东| 天津市| 南涧| 偃师市| 方正县| 海淀区| 金川县| 永丰县| 昭通市| 大埔区| 廉江市| 启东市| 和田市| 祁门县| 西乡县| 讷河市| 长垣县| 景泰县| 星子县| 丹巴县| 班戈县| 保亭| 介休市| 融水| 库尔勒市| 莱州市| 南澳县| 汽车| 乌审旗| 休宁县| 光泽县| 金溪县| 福清市| 许昌县| 黄山市| 广德县| 辽阳县| 阿拉善右旗|