作用域
执行期上下文:变量对象 VO、作用域链 Scope、this
作用域 :[[scope]]
存储执行期上下文集合,函数创建时,就会保存所有父变量到其中
作用域链:[[scope]]
中的执行期上下文集合呈链式连接,这种连接称为作用域链
function fun1() {
function fun2() {}
}
// 函数创建时 分析以上两个函数的作用域
fun1.[[scope]] = {
GO
}
fun2.[[scope]] = {
fun1.AO
GO
}
// 函数激活时 将活动对象 AO 加入作用域链最顶端 作用域链创建完毕
fun2.Scope = {
AO
[[scope]] = {
func1.AO
GO
}
}
分析
var scope = "global scope"
function checkscope(){
var scope2 = 'local scope'
return scope2
}
checkscope()
// 1. 函数创建时 保存作用域链到 [[scope]]
checkscope.[[scope]] = {
GO: {
scope: 'global scope'
}
}
// 2. 函数执行
// 1) 创建 checkscope 的执行期上下文然后压入执行期上下文栈
ECStack = {
checkscope.context
global.context
}
// 2) 复制 [[scope]] 属性创建作用域链
checkscope.context = {
checkscope.[[scope]]: {
GO
}
}
// 3) 创建 AO
// AO 创建过程 1.创建AO 2.变量声明 3.形参实参相统一 4.函数体赋值
checkscope.context = {
AO = {
arguments: {
length: 0
},
scope2: undefined
},
checkscope.[[scope]]: {
GO
}
}
// 4) 函数顺序执行
checkscope.context = {
AO = {
arguments: {
length: 0
},
scope2: 'local scope'
},
checkscope.[[scope]]: {
GO
}
}
// 5) 函数执行完返回 scope2, checkscope 函数的执行期上下文出栈销毁