js预编译习题解题思路
function fn(a,c) {
console.log(a) // function a
var a = 123
console.log(a) // 123
console.log(c) // function c
function a() {}
if (false) {
var d =678
}
console.log(d) // undefined
console.log(b) // undefined
var b = function () {}
console.log(b) // function
function c() {}
console.log(c)// function c
}
fn(1,2)
解题思路:
先走预编译阶段、再走代码逐行解释阶段
1、编译阶段
js在作用域创建阶段(预编译阶段):
1、js的变量对象创建AO对象供js引擎访问
2、找形参和变量的声明,作为AO对象的属性名,值为undefined
3、实参和形参值相统一
4、找函数声明,会覆盖变量的声明
变量或参数的声明 | 步骤2 | 步骤3 | 步骤4 | 预编译结果 |
---|---|---|---|---|
a | undefined | 1 | function a() {} | function a() {} |
c | undefined | 2 | function c() {} | function c() {} |
d | undefined | undefined | ||
b | undefined | undefined |
AO对象:
// 产生的AO对象
// 根据预编译阶段 var修饰的内容进行变量提升、函数提升
// AO:{
// a:function a() {}
// c:function c() {}
// d:undefined
// b:undefined
// }
2、代码逐行解释阶段
按照代码逻辑重上向下读代码
答案:
function a
123
function c
undefined
undefined
function
function c