Skip to content

执行上下文

例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();
  1. 执行代码,创建全局执行的上下文,然后压入执行栈
js
ECstack = [
    globalContext
]
ECstack = [
    globalContext
]
  1. 初始化全局上下文
js
globalContext = {
    VO:[global],
    Scope:[globalContext.VO],
    this:[globalContext.VO]
}
globalContext = {
    VO:[global],
    Scope:[globalContext.VO],
    this:[globalContext.VO]
}
  1. 创建 checkscope 函数,保存作用域链 到函数的[[scope]]属性
js
checkscope.[[scope]] =[
    globalContext.Vo
]
checkscope.[[scope]] =[
    globalContext.Vo
]
  1. 执行 checkscope 函数,创建checkscope函数的执行上下文,然后压入 执行栈
js
ECstack = [
    checkscopeContext,
    globalContext
]
ECstack = [
    checkscopeContext,
    globalContext
]
  1. 初始化checkscopeContext
    1. 复制作用域链[[scope]]
    2. 使用arguments对象创建活动对象
    3. 初始化活动对象
    4. 将活动对象压入作用域链顶部
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
}
  1. 执行f函数,创建 f 函数的执行上下文,然后压入执行栈
js
ECstack = [
    fContext,
    checkscopeContext,
    globalContext
]
ECstack = [
    fContext,
    checkscopeContext,
    globalContext
]
  1. 初始化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
}
  1. 执行f函数,沿着作用域链查找到scope,然后返回其值
  2. f执行完毕,弹出执行栈
js
ECstack = [
    checkscopeContext,
    globalContext
]
ECstack = [
    checkscopeContext,
    globalContext
]
  1. 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()();
  1. ...未完待续

更新于: