执行上下文与执行上下文栈
1.变量提升与函数提升
变量声明提升
- 通过var定义(声明)的变量,在定义语句之前就可以访问到
- 值:undefined
函数声明提升
- 通过function声明的函数,在之前就可以直接调用
- 值:函数定义(对象)
var a = 3
function fn() {
console.log(a) // undefined
var a = 4
}
fn()
console.log(b) // unfefined 变量提升
fn2() //可调用 函数提升
var b = 3
function fn2() {
console.log('fn2()')
}
问题:变量提升和函数提升是如何产生的?
变量提升和函数提升引申出执行上下文和执行上下文栈
2.执行上下文
全局执行上下文
-
在执行全局代码前将window确定为全局执行上下文
-
对全局数据进行预处理
- var定义的全部变量---->undefined,添加为window的属性
- function声明的全局函数---->赋值(fun),添加为window的方法
- this---->赋值(window)
-
开始执行全局代码
函数执行上下文(虚拟的,存在于栈中)
-
在调用函数,准备执行函数体之前,创建对应的函数执行上下文对象
-
对局部数据进行预处理
- 形参变量---->赋值(实参)---->添加为执行上下文的属性
- arguments---->赋值(实参列表),添加为执行上下文的属性
- var定义的局部变量---->undefined,添加执行上下文的属性
- function声明的函数---->赋值(fun),添加执行上下文的属性
- this---->赋值(调用函数的对象)
-
开始执行函数体代码
// 函数执行上下文
function fn(a1) {
console.log(a1) // 2
console.log(a2) // undefined
a3() // a3()
console.log(this) // window
console.log(arguments) // 伪数组(2, 3)
var a2 = 3
function a3() {
console.log('a3()')
}
}
fn(2, 3)
3.执行上下文栈
- 在全局代码执行前,JS引擎就会创建一个栈来存储管理所有的执行上下文对象
- 在全局执行上下文(window)确定后,将其添加到栈中(压栈)
- 在函数执行上下文创建后,将其添加到栈中(压栈)
- 在当前函数执行完后,将栈顶的对象移除(出栈)
- 当所有的代码执行完后,栈中只剩下window
<script type="text/javascript">
//1.进入全局执行上下文
var a = 10
var bar = function (x) {
var b = 5
foo(x + b) // 3.进入foo执行上下文
}
var foo = function (y) {
var c = 5
console.log(a + c + y)
}
bar(10) // 2.进入bar函数执行上下文
</script>
图解
注意:栈底的执行上下文一定是window,总在底部
面试题:
1).
<script type="text/javascript">
console.log('gb:' + i)
var i = 1
foo(1)
function foo(i) {
if(i == 4) {
return
}
console.log('fb:' + i)
foo(i + 1) // 递归函数
console.log('fe: ' + i)
}
console.log('ge:' + i)
// 1.依次输出什么?
// gb:undefined
// fb:1
// fb:2
// fb:3
// fe:3
// fe:2
// fe:1
// fe:1
// 2.整个过程中产生了几个执行上下文? 5个
</script>
2).
// 先执行变量提升,再执行函数提升
function a() {}
var a;
console.log(typeof a) // 'function'
if(!(b in window)) {
var b = 1
}
console.log(b) // undefined
3).
var c = 1
function c(c) {
console.log(c)
}
c(2) //报错 c不是function 变量提升