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

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

主站蜘蛛池模板: 锦州市| 鄂托克旗| 靖安县| 沈阳市| 霍山县| 赤壁市| 井研县| 腾冲县| 韶山市| 长沙县| 怀远县| 青阳县| 中山市| 营山县| 孟州市| 罗源县| 延吉市| 南江县| 万安县| 铜山县| 龙门县| 吉林市| 老河口市| 连山| 蓬莱市| 福清市| 鹤峰县| 丘北县| 新巴尔虎右旗| 云安县| 六盘水市| 汉川市| 惠东县| 滕州市| 郴州市| 固阳县| 鹤岗市| 洮南市| 富民县| 玉龙| 广宗县|