Do you think i is a global variable? Since i is a local variable, what is the relationship between i in f1 and i in f2?
As for why it is 0, 1 instead of 1, 2. That’s because i++ is actually i = i + 1; console.log(i++), i is printed first, and then i = i + 1 is executed ; If you change it to console.log(++i); then it will be 1 or 2.
When f1 is executed for the first time, 0 is output. Because it is i++, i is output first and then added. When executed again, i is 1 at this time. Similarly, 2 is output. When f2 is executed, because i is 0, 0 is output. That is to say, the scopes of f1 and f2 are different, so the references of i are also different.
0 is that console.log will be executed first and then i will be incremented. However, the i in f1 and f2 are not related, and because of the closure, executing f1 again will get 1.
Do you think i is a global variable?
Since i is a local variable, what is the relationship between i in f1 and i in f2?
As for why it is 0, 1 instead of 1, 2.
That’s because i++ is actually i = i + 1;
console.log(i++), i is printed first, and then i = i + 1 is executed ;
If you change it to console.log(++i); then it will be 1 or 2.
This is the difference between i++ and ++i, i++ is quoted first and then incremented, ++i is first incremented and then quoted
When f1 is executed for the first time, 0 is output. Because it is i++, i is output first and then added. When executed again, i is 1 at this time. Similarly, 2 is output. When f2 is executed, because i is 0, 0 is output. That is to say, the scopes of f1 and f2 are different, so the references of i are also different.
f1() is execution
And i is the internal variable of f1. After ++, it will naturally output 0, 1
You can understand it by just adding one line to your code
The newly added console.log will only be executed when var f1 = foo() and f1() will not be executed
i++
is arithmetic first and then addition and subtraction, so it outputs 0 first and then changes to 1Because ++ is a post-operation self-add operator. i will be incremented after completing this instruction.
The reason for
0 is that console.log will be executed first and then i will be incremented. However, the i in f1 and f2 are not related, and because of the closure, executing f1 again will get 1.