Skip to content

Commit 964ed57

Browse files
committed
closure
1 parent 5b19579 commit 964ed57

39 files changed

+321
-417
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
The answer is: **Pete**.
2+
3+
A function gets outer variables as they are now, it uses the most recent values.
4+
5+
Old variable values are not saved anywhere. When a function wants a variable, it takes the current value from its own Lexical Environment or the outer one.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
importance: 5
2+
3+
---
4+
5+
# Does a function pickup latest changes?
6+
7+
The function sayHi uses an external variable name. When the function runs, which value is it going to use?
8+
9+
```js
10+
let name = "John";
11+
12+
function sayHi() {
13+
alert("Hi, " + name);
14+
}
15+
16+
name = "Pete";
17+
18+
sayHi(); // what will it show: "John" or "Pete"?
19+
```
20+
21+
Such situations are common both in browser and server-side development. A function may be scheduled to execute later than it is created, for instance after a user action or a network request.
22+
23+
So, the question is: does it pick up the latest changes?

1-js/06-advanced-functions/03-closure/lexenv-nested-work.svg renamed to 1-js/06-advanced-functions/03-closure/2-closure-variable-access/lexenv-nested-work.svg

+1-1
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
The answer is: **Pete**.
2+
3+
The `work()` function in the code below gets `name` from the place of its origin through the outer lexical environment reference:
4+
5+
![](lexenv-nested-work.svg)
6+
7+
So, the result is `"Pete"` here.
8+
9+
But if there were no `let name` in `makeWorker()`, then the search would go outside and take the global variable as we can see from the chain above. In that case the result would be `"John"`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
importance: 5
2+
3+
---
4+
5+
# Which variables are available?
6+
7+
The function `makeWorker` below makes another function and returns it. That new function can be called from somewhere else.
8+
9+
Will it have access to the outer variables from its creation place, or the invocation place, or both?
10+
11+
```js
12+
function makeWorker() {
13+
let name = "Pete";
14+
15+
return function() {
16+
alert(name);
17+
};
18+
}
19+
20+
let name = "John";
21+
22+
// create a function
23+
let work = makeWorker();
24+
25+
// call it
26+
work(); // what will it show?
27+
```
28+
29+
Which value it will show? "Pete" or "John"?

0 commit comments

Comments
 (0)