JavaScript closure (from an interview question)

Time:2020-11-25

First look at a piece of code and come up with your own answer:

    for(var i=0;i<5;i++){
        setTimeout(function(){
            console.log(i);
        },1000)
    }
    
    console.log(i);

The answer to this question is 5555555.
One 5 is output immediately, and five 5 are output after 1 second.

If we want to change the answer here into: 5 1 2 3 4 5.
Well, those who are familiar with closures can quickly come up with a method like this:

    for(var i=0;i<5;i++){
        (function(j){   //j = i
            setTimeout(function(){
                console.log(j);
            },1000)
        })(i);
    }
    
    console.log(i);

If you know a lot about timers, we can use another way:

    for(var i=0;i<5;i++){
        setTimeout(function(j){
            console.log(j);
        },1000,i)
    }
    
    console.log(i);

The third parameter of setTimeout here is optional and represents other parameters provided to the currently executing function

Of course, if you are familiar with ES6 syntax, you will soon think of changing VaR to let. The code is as follows:

    for(let i=0;i<5;i++){
        setTimeout(function(){
            console.log(i);
        },1000)
    }
    
    console.log(i);

Of course, this method will report an error, because the I value is only valid in block level scope;
But this method can change the result printed in the timer to 1 2 3 4 5

Closure, generally speaking, is that one function can access the variables in another function to avoid the variables being recycled by garbage collection mechanism.

The most common closure is to add a sub function inside the function, and access the local variables of the function through the sub function.

Recommended Today

Summary of recent use of gin

Recently, a new project is developed by using gin. Some problems are encountered in the process. To sum up, as a note, I hope it can help you. Cross domain problems Middleware: func Cors() gin.HandlerFunc { return func(c *gin.Context) { //Here you can use * or the domain name you specify c.Header(“Access-Control-Allow-Origin”, “*”) //Allow header […]