[ Web Proxy ]
URL:
Viewing:
https://raw.githubusercontent.com/pagers-org/JavaScriptCrash/main/Javascript/closure.md
[Back]
[Original]
. , . , ` (Lexical environment)`. ## > , ( ) . [](https://github.com/FECrash/JavascriptCrash/blob/mainner/Javascript/scope.md) . ? ```js const x = 1; function outer(){ const x = 10; inner(); } function inner(){ console.log(x); } outer(); // 1 inner(); // 2 ``` outer inner . . , . , ` ` ** (Scope Chainner)** . ** ( ) () **.
## `[[Environment]]` > `[[Environment]]` . () () . , `[[Environment]]` , . ( ) , ( ) . `[[Environment]]` . (Control) , . 1. 2. 1. 2. this 3. ` ` `[[Environment]]` , . . , . .
## > (Closure) . . . ```js const x = 1; function outer(){ const x = 10; return function() { console.log(x); }; } const exec = outer(); // exec(); // 10 ``` 1. `const exec = outer();` outer outer (pop). 2. outer `const x = 10;` . 3. x , 1 ****. outer x `10` . ** , **. outer `[[Environment]]` outer . outer outer . , [-(Mark-and-sweep) ](https://developer.mozilla.org/ko/docs/Web/JavaScript/Memory_Management#mark-and-sweep_algorithm) Garbage Collection . , outer `[[Environment]]` , exec Garbage Collection . Garbage Collector ! . . ? ```js const x = 1; function outer(){ const y = 10; // * . return function() { console.log(x); }; } const exec = outer(); // exec(); // 1 ``` . ? , . y . . . . . ` (Free Variable)` ` ` .
## > (State) . (Encapsulation) . . , (Information Hiding) . . (, Coupling) . ... . . ```js // // counter . function makeCounter(predicate) { // let counter = 0; // return function () { // counter = predicate(counter); return counter; }; } // function increase(n) { return ++n; } // function decrease(n) { return --n; } // . // makeCounter . const increaser = makeCounter(increase); console.log(increaser()); // 1 console.log(increaser()); // 2 // increaser . const decreaser = makeCounter(decrease); console.log(decreaser()); // -1 console.log(decreaser()); // -2 ``` makeCounter . makeCounter counter . ? makeCounter ** ** . , makCounter . (State) . **(Share)** . ```js // // counter . const counter = (function () { // let counter = 0; // return function (predicate) { // . counter = predicate(counter); return counter; }; }()); // function increase(n) { return ++n; } // function decrease(n) { return --n; } // . console.log(counter(increase)); // 1 console.log(counter(increase)); // 2 // . console.log(counter(decrease)); // 1 console.log(counter(decrease)); // 0 ``` ** ** .
> 2021-10-04, ## ### - (Lexical Environment) ** ** , `this`... ? ! ### - ** - [Link](https://www.hanumoka.net/2017/08/31/javascript-20170831-javascript-closure-3/)
Web Proxy Viewer |
New URL
|
Original Page