执行上下文
例1分析
js
var scope = "global scope";
function checkscope(){
var scope = "local scope";
function f(){
return scope;
}
return f();
}
checkscope();
var scope = "global scope";
function checkscope(){
var scope = "local scope";
function f(){
return scope;
}
return f();
}
checkscope();
- 执行代码,创建全局执行的上下文,然后压入执行栈
js
ECstack = [
globalContext
]
ECstack = [
globalContext
]
- 初始化全局上下文
js
globalContext = {
VO:[global],
Scope:[globalContext.VO],
this:[globalContext.VO]
}
globalContext = {
VO:[global],
Scope:[globalContext.VO],
this:[globalContext.VO]
}
- 创建 checkscope 函数,保存作用域链 到函数的
[[scope]]
属性
js
checkscope.[[scope]] =[
globalContext.Vo
]
checkscope.[[scope]] =[
globalContext.Vo
]
- 执行 checkscope 函数,创建checkscope函数的执行上下文,然后压入 执行栈
js
ECstack = [
checkscopeContext,
globalContext
]
ECstack = [
checkscopeContext,
globalContext
]
- 初始化checkscopeContext
- 复制作用域链
[[scope]]
- 使用
arguments
对象创建活动对象 - 初始化活动对象
- 将活动对象压入作用域链顶部
- 复制作用域链
js
checkscopeContext = {
AO:{
arguments:{
length:0
},
scope:undefined,
f:reference to function f(){}
},
Scope:[AO,globalContext.Vo]
this:undefined
}
checkscopeContext = {
AO:{
arguments:{
length:0
},
scope:undefined,
f:reference to function f(){}
},
Scope:[AO,globalContext.Vo]
this:undefined
}
- 执行f函数,创建 f 函数的执行上下文,然后压入执行栈
js
ECstack = [
fContext,
checkscopeContext,
globalContext
]
ECstack = [
fContext,
checkscopeContext,
globalContext
]
- 初始化fContext
js
fContext = {
AO:{
arguments:{
length:0
}
},
Scope:[AO,checkscopeContext.VO,globalContext.VO],
this:undefined
}
fContext = {
AO:{
arguments:{
length:0
}
},
Scope:[AO,checkscopeContext.VO,globalContext.VO],
this:undefined
}
- 执行f函数,沿着作用域链查找到scope,然后返回其值
- f执行完毕,弹出执行栈
js
ECstack = [
checkscopeContext,
globalContext
]
ECstack = [
checkscopeContext,
globalContext
]
- checkscope执行完毕,弹出执行栈
js
ECStack = [
globalContext
];
ECStack = [
globalContext
];
例2分析
js
var scope = "global scope";
function checkscope(){
var scope = "local scope";
function f(){
return scope;
}
return f;
}
checkscope()();
var scope = "global scope";
function checkscope(){
var scope = "local scope";
function f(){
return scope;
}
return f;
}
checkscope()();
- ...未完待续