|
|
以上是困惑的问题?为什么nAdd()影响最近的闭包。
stackoverflow的两个答案,合起来能很好的理解这个问题。
1.进一步明白细节的回答
It has to do with when nAdd is assigned the function. Note that when you create a closure, a new “copy” (for lack of a better word) of the local variables are created. Thus, result1’s n is different from result2s n which is different from result3’s n. They are seperate, and each closure cannot access another closure’s n.
Look at this line:
|
|
This assigns nAdd a new closure each time. Each time, this closure will only affect the most recent “copy” of n.
So when you are doing.
|
|
nAdd got assigned a new closure each time. The last time, nAdd got assigned a closure with result3’s copy of n.
Thus, when you do nAdd(), you only increment result3’s n.
Here’s an example that might clear things up.
|
|
To further elaborate, consider what would happen if you did this instead:
|
|
Or this:
|
|
It becomes obvious that nAdd updates only the most recent invocation’s n.!
2.调用本质的回答
First, you need to be clear about the following thing:
nAdd is a global scoped function. But it is using a local scoped variable n.
Every time you re-create f1(), the pointer of nAdd function will change.
Finally it will changed to the closest f1() closure and the n variable inside nAdd function will also point to the closest f1() closure. So it can only change the value of the closest one.