(function(){
for(var i = 0; i < 5; i++) {}
console.log(i) // i = 5
})()
First question: Which part of js knowledge does this belong to?
Second question: Explain in layman’s terms why i is equal to 5?
0o0
PHP中文网2017-06-12 09:31:37
Is this problem a closure? I don’t think it is a closure, and there is no nesting of functions. It is a problem of function local variables and anonymous functions.
Creating an anonymous function and executing it immediately does not involve closures. Just when the loop ends, the value of i
becomes 5
and exits the loop, console.log(i)
prints the current i
, which is 5.
This is equivalent to:
var test = function() {
for(var i = 0; i < 5; i++) {}
console.log(i) // i = 5
}
test();
扔个三星炸死你2017-06-12 09:31:37
This is not a closure, it’s just a value printed after the for loop speed
怪我咯2017-06-12 09:31:37
This is a problem caused by js not having block-level scope, only function scope. . . Ju can directly pull the closure. . . I accept it. . .
伊谢尔伦2017-06-12 09:31:37
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.
怪我咯2017-06-12 09:31:37
This usually appears in the problem of examining closures
i + 1 looped 5 times, so i is 5
ringa_lee2017-06-12 09:31:37
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