Close the classic interview questions and ask you for advice.

first of all, there is a front-end classic closure interview question.

for(var i = 0;i<5;iPP){
  setTimeout(()=>{
    console.log(i)
  },1000*i)
}
Everyone knows that the answer to this question is to type 5 every second.

then the interviewer asked the interviewer to output the correct number every 1 second, and you know to use closures:

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

but the only way to do this is to use the function scope to save the value of I, so that the value of the variable found by the timer when performing the callback is the corresponding value of each loop, and the function of the closure is to give the outside of the function indirect access to the value inside the function.

so in a nutshell, I think this problem is not the function of closure, but just the function of function scope.

I don"t know if my understanding is correct.

Mar.02,2021

for(let i = 0;i<5;iPP){
  setTimeout(()=>{
    console.log(i)
  },1000*i)
}//0,1,2,3,4

generally this routine allows you to write immediately execute the function expression , of course, the more capricious will be changed to let.

for(var i = 0;i<5;iPP){
  (setTimeout((j)=>{
    console.log(j)
  },1000*j))(i)
}
The

closure should refer to the original topic, and the callback of setTimeout refers to the variable iPersoni that does not fall within its scope and cannot be released in the original scope. Of course, you can also understand that all asynchronous operations are closures.

the definition of closures in JavaScript that you don't know

produces a closure when a function can remember and access its lexical scope, even if the function is executed outside the current lexical scope. -JavaScript you don't know

your answer is correct, but scope is closely related to closures. It's easy to feel that there are no closures here, but in fact this is about lexical scope. The following two pieces of code, 1 in lexical scope and 2 outside lexical scope.

function a(){
    function b(){
    }
}
function a(){
    setTimeout(function b(){
    },0);
}

you are right. Half!

 
The expected behavior of 

closures is to enclose references to external memory in functions, but JS programmers have no idea of pointer memory addresses and will think that the first case is wrong, but that's the right thing to do.

as for how to change the result to the second case has nothing to do with the concept of closure, different languages have different solutions, people often step into this hole in JS and enjoy talking about it.

Menu