闭包的概念及利用场景

闭包就是指那些可能拜访自在变量的函数

自在变量指函数中应用的,既不是函数从参数也不是函数局部变量的变量

  1. 从实践角度: 所有的函数都是闭包。
  2. 从理论角度:

    • 即便创立他的上下午曾经销毁,它依然存在(比方:外部函数,从父函数返回)
    • 代码中援用了自在变量

援用场景

  1. 柯里化函数
    防止频繁调用具备雷同参数的函数,同时又能够轻松服用

封装一个高阶函数

function getArea(width, height) {    return width * height;}const area1 = getArea(10, 20);const area2 = getArea(10, 30);const area3 = getArea(10, 40);function getArea(width) {    return (height) => {        return width * height;    }}const getTenWidthArea = getArea(10);const area2 = getTenWidthArea(30);const area3 = getTenWidthArea(40);
  1. 实现公有办法/变量
    其实就是模块的形式,现代化的打包最终其实就是每个模块的代码我的项目独立
  2. 匿名自执行函数

    var fun = (function() { var num = 0; return function() {     num++;     return num; }})();console.log(fun())console.log(fun())console.log(fun())
  3. 缓存一些后果
    在内部函数创立一个数组,闭包函数能够更改/获取数组的值

    function funParent() { let memo = []; // 生命周期被缩短了 function funTwo(i) {     memo.push(i);     console.log(memo) } return funTwo}const fn = funParent();fn(1)fn(2)

    练习题

  4. 第一个

    // 实现一个compose 函数,用法如下function fn1(x) { return x + 1}function fn2(x) { return x + 2}function fn3(x) { return x + 3}function fn4(x) { return x + 4}const a = compose(fn1, fn2, fn3, fn4);console.log(a(5)) // 1+4+3+2+1// 实现形式// args数组列表 对应fn1, fn2, fn3, fn4function compose(...args) { return (x) => {     let arr = args.reduce((sum,cur) =>{         return cur(sum)     }, x)     return arr }}
  5. 第二个

    function currying(fn, ...args) { const originLenth = fn.length; let allArgs = [...args]; const resFn = (...newArgs) => {     // 把屡次传入的参数整合起来     allArgs = [...allArgs, ...newArgs];     if (allArgs.length === originLenth) {         // 长度相等的时候间接指向传入的fn函数拿到返回值         return fn(...allArgs)     } else {         return resFn     } } return resFn}const add = (a, b, c) => a+b+c;const a1 = currying(add, 1)const a2 = a1(2);console.log(a2(3))// const add = (a, b, c, f) => a+b+c+f;// const a6 = currying(add, 1, 2, 9, 28)// console.log(a6())

总结

  1. 创立公有变量
  2. 缩短变量生命周期