JS closure details

Time:2022-4-10

Closure (three points)

definition

Closures are nested functions, and inner functions are closures

characteristic

Normally, the internal variables will be destroyed after the function is executed
The internal function of the closure is not completed, and the external function variables will not be destroyed.
//Closure
 function outerfun() {
        let a = 10;// Destroy after feature execution
        Function innerfun() {// internal function
            console.log(a);
        }
        return innerFun;
    }
    let fun = outerfun();/* The assignment of outerfun to fun as the return value is not completed
    So there are 10. If the internal function is called, the external function will not be destroyed*/


    fun();//10

Application (closure can encapsulate a piece of code)

//Apply 
    //Not encapsulated
    let aa = 10;// global variable
    let bb = 20;
    function add() {
        return aa + bb;
    }
    function sub() {
        return aa - bb;
    }
    let res1 = add();
    let res2 = sub();
    console.log(res1, res2);//30.-10

Use closure encapsulation

//Closure encapsulation uses closures to realize modular functions
    Let modouble = (function() {// anonymous function
        let aa = 10;// local variable
        let bb = 20;
        function add() {
            return aa + bb;
        }
        function sub() {
            return aa - bb;
        }
        return {
            add: add,
            sub: sub,
        }
    }) () // call directly after the parentheses are declared
    let ress = modouble.add();
    let resss = modouble.sub();
    console.log(ress, resss);//30,-10