Is this problem a closure?I don’t think it is a closure, andthere is no nesting of functions. It is a problem offunction local variablesandanonymous functions.
Creating an anonymous function and executing it immediately does not involve closures. Just when the loop ends, the value ofibecomes5and exits the loop,console.log(i)prints the currenti, which is 5.
This is equivalent to:
var test = function() { for(var i = 0; i < 5; i++) {} console.log(i) // i = 5 } test();
There is no such thing as block-level scope in JavaScript, so the variables inside the for loop {} and if statement {} can be accessed from the outside.
Scope is divided into global scope and local scope
The global scope is built in by the system for you when you create a document. Local scope is achieved by creating a function.
Is this problem a closure?I don’t think it is a closure, andthere is no nesting of functions. It is a problem offunction local variablesandanonymous functions.
Creating an anonymous function and executing it immediately does not involve closures. Just when the loop ends, the value of
i
becomes5
and exits the loop,console.log(i)
prints the currenti
, which is 5.This is equivalent to:
This is not a closure, it’s just a value printed after the for loop speed
This is a problem caused by js not having block-level scope, only function scope. . . Ju can directly pull the closure. . . I accept it. . .
There is no such thing as block-level scope in JavaScript, so the variables inside the for loop {} and if statement {} can be accessed from the outside.
Scope is divided into global scope and local scope
The global scope is built in by the system for you when you create a document.
Local scope is achieved by creating a function.
This usually appears in the problem of examining closures
i + 1 looped 5 times, so i is 5
You should want to know about closures in js
Because the for loop execution is completed when console.log is executed, i is naturally equal to 5
Let’s take a look at closures combined with timers, or event binding
Closures in js,