An example closure

    function f1() {
        let a = 0
        function f2() {
            a++
            return a
        }
        return f2
    }
    const result = f1()
    const b1 =result() // b1 = 1
    const b2 =result() // b2 = 2
Copy the code

In the example above, because of the closure, a is always in memory, so b1=1,b2=2. Let’s go through it step by step in the browser. Start state, ready to assign f1 to result.

Next assignment, we find one firstLocalThis is called the local execution context and is created at the time the function is executed and destroyed at the end. That’s why functions don’t hold values if we don’t apply closures. His variables will be destroyed.

And then we go to the next red box,ClosureThe closure protagonist comes in and we see thatf2Because of the use off1. So I have one more closure that holdsa. The equivalent ofaThis variable is saved.

We continue when the call toconst b1 =result()At the right time.result() Be implemented. When callingaIn fact, a doesn’t exist anymore, but because of the closure, it will take the value from the closure first. Lambda is 0 plus lambda. All b1’s equal to 1.

Similarly, in execution,ClousreIt’s 1, plus plus, so b2 is equal to 2

So what is a closure

Now when we talk about closures, it’s more like how to form closures. A function uses the variables of its outer function. So let’s say that this forms a closure. I understand that closures are more like a backpack, a space. Because of the nature of the JS closure, store the variables used in the outer function.

The role of closures

A variable that exists inside a closure can be used as a global variable and cannot be easily contaminated. It can also be used as a private variable of an object.