closure
This commit is contained in:
parent
5b195795da
commit
964ed57c42
39 changed files with 365 additions and 461 deletions
File diff suppressed because one or more lines are too long
After Width: | Height: | Size: 61 KiB |
|
@ -0,0 +1,9 @@
|
|||
The answer is: **Pete**.
|
||||
|
||||
The `work()` function in the code below gets `name` from the place of its origin through the outer lexical environment reference:
|
||||
|
||||

|
||||
|
||||
So, the result is `"Pete"` here.
|
||||
|
||||
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"`.
|
|
@ -0,0 +1,29 @@
|
|||
importance: 5
|
||||
|
||||
---
|
||||
|
||||
# Which variables are available?
|
||||
|
||||
The function `makeWorker` below makes another function and returns it. That new function can be called from somewhere else.
|
||||
|
||||
Will it have access to the outer variables from its creation place, or the invocation place, or both?
|
||||
|
||||
```js
|
||||
function makeWorker() {
|
||||
let name = "Pete";
|
||||
|
||||
return function() {
|
||||
alert(name);
|
||||
};
|
||||
}
|
||||
|
||||
let name = "John";
|
||||
|
||||
// create a function
|
||||
let work = makeWorker();
|
||||
|
||||
// call it
|
||||
work(); // what will it show?
|
||||
```
|
||||
|
||||
Which value it will show? "Pete" or "John"?
|
Loading…
Add table
Add a link
Reference in a new issue