11## Closures and References
22
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
66[ function scope] ( #function.scopes ) , all functions, by default, act as closures.
77
88### Emulating private variables
@@ -24,7 +24,7 @@ defined in. Since the only scoping that JavaScript has is
2424 foo.increment();
2525 foo.get(); // 5
2626
27- Here, ` Counter ` returns ** two** closures. The function ` increment ` as well as
27+ Here, ` Counter ` returns ** two** closures: the function ` increment ` as well as
2828the function ` get ` . Both of these functions keep a ** reference** to the scope of
2929` Counter ` and, therefore, always keep access to the ` count ` variable that was
3030defined in that very scope.
@@ -58,8 +58,8 @@ copying the value of the loops index variable.
5858The above will ** not** output the numbers ` 0 ` through ` 9 ` , but will simply print
5959the number ` 10 ` ten times.
6060
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
6363` i ` as been set to ` 10 ` .
6464
6565In 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`.
8484The anonymous function that gets passed to ` setTimeout ` now has a reference to
8585` e ` , whose value does ** not** get changed by the loop.
8686
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
8989above.
9090
9191 for(var i = 0; i < 10; i++) {
0 commit comments