每個執行環境包含:
var/function 聲明綁定。this 指向的值。eval → 建立**eval 執行環境**。全域代碼:
window / globalThis)函數代碼:
[[Environment]](閉包關鍵)。var/function 綁在這裡)。| 呼叫方式 | This 指向 | 嚴格模式 |
|---|---|---|
new Fn() | 新建實例 | 同 |
fn.call/apply/bind(obj) | 指定 obj | 同 |
obj.method() | obj | 同 |
fn() (獨立調用) | 全域物件 | undefined |
| 箭頭函數 | **詞法作用域的 this** | 同 |
undefined)。undefined。function outer() {
const secret = "hidden";
return function inner() {
console.log(secret); // 內部函數引用外部詞法環境的變量
};
}
const fn = outer();
fn(); // "hidden" — inner 的 [[Environment]] 指向 outer 的詞法環境
**閉包 = 函數 + 其定義時的詞法環境引用**。
(0, eval)("..."))。// 1. 查看當前作用域鏈(DevTools Sources -> Scope 面板)
// 2. 判斷 this
console.log("this:", this, new.target); // new.target 判斷是否為 new 調用
// 3. 檢測 TDZ
{
// console.log(x); // ReferenceError: Cannot access 'x' before initialization
let x = 1;
}
// 4. 閉包檢查
function createCounter() {
let count = 0;
return () => ++count; // count 被閉包捕獲
}
const c1 = createCounter();
console.dir(c1); // Scope -> Closure (createCounter) -> count: 0
執行環境棧 (Execution Context Stack)
├── Global EC
│ ├── LexicalEnv: GlobalEnv (window)
│ ├── VariableEnv: GlobalEnv
│ └── ThisBinding: window
│
├── Function EC (foo)
│ ├── LexicalEnv: FunctionEnv { outer: GlobalEnv }
│ ├── VariableEnv: FunctionEnv
│ └── ThisBinding: obj (obj.foo())
│
└── Function EC (bar)
├── LexicalEnv: FunctionEnv { outer: FunctionEnv(foo) } ← 閉包鏈
├── VariableEnv: FunctionEnv
└── ThisBinding: undefined (strict mode call)