1
1
## Closures and References
2
2
3
- One of JavaScript's most powerful features is the availability of * closures* ,
4
- this means that scopes ** always** keep access to the outer scope they were
5
- defined in . Since the only scoping that JavaScript has is
3
+ One of JavaScript's most powerful features is the availability of * closures* .
4
+ With closures, scopes ** always** keep access to the outer scope, in which they
5
+ were defined . Since the only scoping that JavaScript has is
6
6
[ function scope] ( #function.scopes ) , all functions, by default, act as closures.
7
7
8
8
### Emulating private variables
@@ -24,7 +24,7 @@ defined in. Since the only scoping that JavaScript has is
24
24
foo.increment();
25
25
foo.get(); // 5
26
26
27
- Here, ` Counter ` returns ** two** closures. The function ` increment ` as well as
27
+ Here, ` Counter ` returns ** two** closures: the function ` increment ` as well as
28
28
the function ` get ` . Both of these functions keep a ** reference** to the scope of
29
29
` Counter ` and, therefore, always keep access to the ` count ` variable that was
30
30
defined in that very scope.
@@ -58,8 +58,8 @@ copying the value of the loops index variable.
58
58
The above will ** not** output the numbers ` 0 ` through ` 9 ` , but will simply print
59
59
the number ` 10 ` ten times.
60
60
61
- The * anonymous* function keeps a ** reference** to ` i ` and at the time
62
- ` console.log ` gets called, the ` for loop ` has already finished and the value of
61
+ The * anonymous* function keeps a ** reference** to ` i ` . At the time
62
+ ` console.log ` gets called, the ` for loop ` has already finished, and the value of
63
63
` i ` as been set to ` 10 ` .
64
64
65
65
In order to get the desired behavior, it is necessary to create a ** copy** of
@@ -84,8 +84,8 @@ argument and will receive a copy of the **value** of `i` as its parameter `e`.
84
84
The anonymous function that gets passed to ` setTimeout ` now has a reference to
85
85
` e ` , whose value does ** not** get changed by the loop.
86
86
87
- There is another possible way of achieving this; that is to return a function
88
- from the anonymous wrapper, that will then have the same behavior as the code
87
+ There is another possible way of achieving this, which is to return a function
88
+ from the anonymous wrapper that will then have the same behavior as the code
89
89
above.
90
90
91
91
for(var i = 0; i < 10; i++) {
0 commit comments