js预编译
总结:
1.未经声明的变量归window所有,全局声明的变量为window一个属性
2.三步曲,对比函数预编译仅仅缺少形参实参统一:
(1)生成一个GO对象 (Global Object) GO ===window
(2)找变量声明,将变量声明名作为GO属性名,值为undefined
(3)找函数声明,值赋予函数体,注意不是函数表达式
global = 100;
function fn(){
console.log(global);
global = 200;
console.log(global);
var global = 300;
}
fn();
var global;
结果为
a=100;
console.log(demo)
function demo(e){
function e(){}
arguments[0] =2;
console.log(e);
if(a){
var b = 123;
function c(){
//...
}
}
var c;
a=10;
var a;
console.log(b);
f=123;
console.log(c);
console.log(a);
}
var a;
demo(1);
console.log(a);
console.log(f);
预编译
1.首先生成GO
2.找变量声明 var a 赋值 undefined
GO{
a:undefined
}
3.找函数声明 function demo(){...} 赋值函数体
GO{
a:undefined
demo:function demo(){...}
}
执行
1.a=100 改变GO中a的值
GO{
a:100
demo:function demo(){...}
}
2.console.log(demo) 打印function demo(e){...}
3.跳过函数声明,跳过 var a
4.demo(1) 执行函数前先函数预编译
函数预编译
1.生成AO{}
2.形参和变量声明赋值为undefined
AO{
e:undefined
b:undefined
c:undefined
a:undefined
}
3.形参实参统一
AO{
e:1
b:undefined
c:undefined
a:undefined
}
4.函数声明
AO{
e:function e(){}
b:undefined
c:undefined
a:undefined
}
新标准if(){}中不可以定义函数,所以此处c未改变
编译完成执行函数
4-1.跳过function e(){}
4-2.arguments[0] =2; arguments[0]与形参e映射,虽为两个个体,值改变时另一个改变
AO{
e:2
b:undefined
c:undefined
a:undefined
}
4-3.console.log(e) 结果为2
4-4.if(a)条件不成立 不执行
4-5.跳过var c;
4-6.a=10;a赋值为10
AO{
e:2
b:undefined
c:undefined
a:10
}
4-7.console.log(b) 结果为undefined
4-8.f=123;未声明的变量为window的属性,GO中f赋值为123
GO{
a:100
demo:function demo(){...}
f:123
}
4-9.console.log(c) 结果为undefined
4-10.console.log(a) 结果为10
5.console.log(a) 结果为100
6.console.log(f) 结果为123
结果为