closure
This commit is contained in:
parent
5b195795da
commit
964ed57c42
39 changed files with 365 additions and 461 deletions
|
@ -0,0 +1,5 @@
|
|||
The answer: **0,1.**
|
||||
|
||||
Functions `counter` and `counter2` are created by different invocations of `makeCounter`.
|
||||
|
||||
So they have independent outer Lexical Environments, each one has its own `count`.
|
|
@ -0,0 +1,31 @@
|
|||
importance: 5
|
||||
|
||||
---
|
||||
|
||||
# Are counters independent?
|
||||
|
||||
Here we make two counters: `counter` and `counter2` using the same `makeCounter` function.
|
||||
|
||||
Are they independent? What is the second counter going to show? `0,1` or `2,3` or something else?
|
||||
|
||||
```js
|
||||
function makeCounter() {
|
||||
let count = 0;
|
||||
|
||||
return function() {
|
||||
return count++;
|
||||
};
|
||||
}
|
||||
|
||||
let counter = makeCounter();
|
||||
let counter2 = makeCounter();
|
||||
|
||||
alert( counter() ); // 0
|
||||
alert( counter() ); // 1
|
||||
|
||||
*!*
|
||||
alert( counter2() ); // ?
|
||||
alert( counter2() ); // ?
|
||||
*/!*
|
||||
```
|
||||
|
Loading…
Add table
Add a link
Reference in a new issue