# 执行上下文栈
JavaScript 引擎并非一行一行地分析和执行程序,而是一段一段地分析执行。当执行一段代码的时候,会进行一个“准备工作”(执行上下文)
变量提升
var foo = function () {
console.log('foo1');
}
foo(); // foo1
var foo = function () {
console.log('foo2');
}
foo(); // foo2
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
函数提升
function foo() {
console.log('foo1');
}
foo(); // foo2
function foo() {
console.log('foo2');
}
foo(); // foo2
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
# 可执行代码
- 全局代码
- 函数代码
- eval代码
# 执行上下文栈?
# 例子
# 例子1
var scope = "global scope";
function checkscope(){
var scope = "local scope";
function f(){
return scope;
}
return f();
}
checkscope();
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
模拟结果
stack.push(checkscope)
stack.push(f)
stack.pop() // f()
stack.pop() // checkscope()
1
2
3
4
2
3
4
# 例子2
var scope = "global scope";
function checkscope(){
var scope = "local scope";
function f(){
return scope;
}
return f;
}
checkscope()();
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
模拟结果
stack.push(checkscope)
stack.pop() // checkscope()
stack.push(f)
stack.pop() // f()
1
2
3
4
2
3
4