- Example a
let a = 1
function fn(){
console.log(a)
}
// Nothing is printed because the function is not executed
Copy the code
- Example 2
let a = 1
function fn(){
console.log(a)
}
fn() / / 1
// we start by declaring a with the value 1, and then call fn to print a.
Copy the code
- Example 3
let a = 1
function fn(){
console.log(a)
}
fn() / / 1
a = 2
// Change the value of a after the function is executed. When the function is executed, a is still 1.
Copy the code
-
From the above example, it can be seen that the determination of the value of a variable in a function needs to determine the timing of the function execution. A value may be declared initially, but may have changed by the time the function is executed.
-
Asynchronous example
let i = 0 for(i = 0; i<6; i++){setTimeout(() = >{ console.log(i) },0)}// 6 Copy the code
Why print six sixes?
- Because of the setTimeout function, the loop is executed once, and the FN of the setTimeout function is queued up after the TodoList. When the for loop ends, there are six events on top, but each event prints the same I that was defined outside the for loop. At the end of the loop, I is 6, so six 6’s are printed out.
What if I want to print out “0, 1, 2, 3, 4, 5”?
for(let i = 0; i<6; i++){setTimeout(() = >{
console.log(i)
},0)}/* Each time the for loop is executed, js creates a new I in memory. The transformation of the values of I does not affect each other. So in TodoList, the I values in the six queued events are independent of each other, so different values are printed out. * /
Copy the code
- or
let i = 0
for(i = 0; i<6; i++){console.log(i)
}//0 1 2 3 4 5
/ * or * /
for (var i = 0; i < 6; i++) {
setTimeout((function(i){
return function() {
console.log(i);
}
}(i)),0)}//0 1 2 3 4 5; Execute this function immediately when I has not changed.
Copy the code