> 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/121zhi-xing-huan-jing-yu-ci-hui-huan-jing/1218fan-wei-lian.md).

# 1.2.1.8.範圍鏈

* 執行下面程式碼

```
function b() {
console.log(myVar);
}

function a() {
var myVar = 2;
b();
}

var myVar = 1;
a();
```

* 會看到
  * 1
* 解析
  * 將會建立對應的執行堆為 ![](https://3195929128-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4M0G8GO2MkGtHfarAf%2F-M4M0IHoyFvfGKjf7P-T%2F-M4M0McqlUnmgR3EYJBX%2F2342.jpg?generation=1586302920892407\&alt=media)
  * 每個Execution context都有自己所參照的**外部環境**, 當需要某個執行環境內的程式碼的變數, 而無法找到變數時, 他會到**外部環境**去尋找變數
  * 搜索範圍鏈到外部環境
    * 每個Execution context參照的外部環境會依照函數的**物理位置**而變動
      * b()會參照的外部環境為Global Execution context
      * a()會參照的外部環境為Global Execution context
  * 若找不到變數會沿著範圍鏈一直向下搜尋
