一個 execution context 包含了一些資訊, 而這些資訊在程式執行期間是必要的, 而這些資訊包含
- LexicalEnvironment
- VariableEnvironment
- ThisBinding
產生 Execution Context 依照程式的不同,而會有三類不同的狀況
1. Entering Global Code
var i = 0;
function test(){console.log("test");}
2. Entering Function Code
function factorial(num)
{
if (num < 0) return -1;
else if (num == 0) return 1;
var result = num;
while (num-- > 2) {
result *= num;
}
return result;
}
factorial(10);
第一次呼叫 factorial
遞迴呼叫(第二次之後), 要注意的是每次 Return 時會退出當時的 execution context, 也就是會從 stack pop 出去, 所以遞迴呼叫並不會造成 stack 一直往上堆
3. Entering Eval Code
當 eval 執行, 前一個 active execution context, 會被當成 calling context 的參考
> eval('var x = 22');
undefined
> x
22
> this.x
22
> window.x
22
> eval('(function() {var y=33; console.log(y);})()');//前一個 active execution context 是匿名 function
33
undefined
> y
ReferenceError: y is not defined
http://www.ecma-international.org/ecma-262/5.1/




0 comments:
Post a Comment