> For the complete documentation index, see [llms.txt](https://jen-hsuan-hsieh.gitbook.io/javascript-node-js/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jen-hsuan-hsieh.gitbook.io/javascript-node-js/chapter1/12javascript-quan-gong-lve-ff1a-ke-fu-js-de-qi-guai-bu-fen/123wu-jian-yu-han-shu/12317le-jie-bi-bao.md).

# 1.2.3.17.了解閉包(一)

* 為什麼sayHi會知道whattosay是甚麼?

  ```
    1 function greet(whattosay) {
    2     return function(name) {
    3         console.log(whattosay + '' + name);
    4     }
    5 }
    6 var sayHi = greet('Hi');
    7 sayHi('Tony');
  ```

  * 執行程式
    * 行1 \~ 5:[全域執行環境 (global Execution context)](https://jenhsuan.gitbooks.io/javascript-node-js/content/chapter1/121zhi-xing-huan-jing-yu-ci-hui-huan-jing/1211quan-yu-huan-jing-yu-quan-yu-wu-jian.html)被建立, 並存放greet()
    * 行6:&#x20;
      * 建立新的[執行環境](https://jenhsuan.gitbooks.io/javascript-node-js/content/chapter1/121zhi-xing-huan-jing-yu-ci-hui-huan-jing/1212zhi-xing-huan-jing-ff1a-chuang-zao-yu-ti-sheng.html), 記憶體會空出whattosay,並賦值 (whattosay: 'Hi')後回傳 (行2 \~ 4)
      * **greeting 的執行環境離開執行堆, 但記憶體還會在, 因此whattosay還在**
    * 行7:&#x20;
      * 呼叫sayHi所指向的函數
      * [全域執行環境 (global Execution context)](https://jenhsuan.gitbooks.io/javascript-node-js/content/chapter1/121zhi-xing-huan-jing-yu-ci-hui-huan-jing/1211quan-yu-huan-jing-yu-quan-yu-wu-jian.html)會存放sayHi, 匿名函數
      * 創造新的[執行環境](https://jenhsuan.gitbooks.io/javascript-node-js/content/chapter1/121zhi-xing-huan-jing-yu-ci-hui-huan-jing/1212zhi-xing-huan-jing-ff1a-chuang-zao-yu-ti-sheng.html), 記憶體會空出name,並賦值 (name: 'Tony')
      * 行3被執行, 這時候因為函數中沒有whattosay的定義, 根據[範圍鍊](https://jenhsuan.gitbooks.io/javascript-node-js/content/chapter1/121zhi-xing-huan-jing-yu-ci-hui-huan-jing/1218fan-wei-lian.html)的觀念會開始向外尋找, 此時還是找的到whattosay, 因為whattosay位於外部的記憶體位置
* 小結
  * 1.雖然greet函數已經結束, 它裡面的函數還是可以參考到**greet函數在記憶體中的位置**到**執行環境中記憶體的位置**
  * 2.執行環境可以把它外部變數關住, 包住, **這種包住所有可以取用的變數的現象稱為閉包**
  * 3.閉包可確保執行函數時可以正常運作, 可以取用到外部變數, 而不用在乎外部函數運行完了沒

![](https://3195929128-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4M0G8GO2MkGtHfarAf%2F-M4M0IHoyFvfGKjf7P-T%2F-M4M0N2b1-492gXvPNQ6%2F123434234.jpg?generation=1586302921374197\&alt=media)
