预编译
- 检查通篇的语法错误
- 预编译的过程
- 解释一行,执行一行
- 函数声明整体提升
- 变量只有声明提升,赋值不提升
var a=b=1; 创建全局变量b=1,var a,a=b a为局部 b为全局
imply global暗示全局变量:。无论声明与否,都存在于window
a = 1
console.log(a); //1 a = window.a = 1
var b = 1
console.log(b); //1 b = window.b = 1
//等同于
window = {
a:1,
b:1
}
function test() {
var a = b = 1
}
test()
console.log(b); //window.b=1 a会报错 window.a为undefined
AO
在函数(JS)执行的前一刻,会创建一个叫做执行期上下文的(AO:活跃对象active object,函数上下文)对象,这个创建执行期上下文的过程叫做预编译。
- 提升:寻找形参和变量声明
- 把实参的参数值赋值给形参
- 寻找函数声明 赋值
- 执行
function test(a) {
console.log(a);
var a = 1
console.log(a);
function a() {}
console.log(a);
var b = function() {} //匿名函数
console.log(b);
function d() {}
}
test(2)
//AO={
// a:undefined ->2 ->function a() {} ->1
// b:undefined ->function() {}
// d:function d() {}
// }
// 结果为:
// ƒ a() {}
// 1
// 1
// ƒ () {}
function test(a,b) {
console.log(a);
c = 0
var c
a = 5
b = 6
console.log(b);
function b() {}
function d() {}
console.log(b);
}
test(1)
// AO= { 变量默认undefined
// a:undifined -> 1 ->5
// c:undifined -> 0
// b:undifined -> function b() {} -> 6
// d:function d() {}
// }
// 结果为1,6,6
GO
GO global object === window 全局上下文
- 找变量、找函数声明
- 执行
先找AO,AO没有再去GO找。先局部再全局
var a = 1
function a() {
console.log(2);
}
console.log(a); //1
//GO = {
// a:undefined -> function a() {} -> 1
//}
function test() {
var a = b = 1 // 相当于 var a, a = b = 1
console.log(b);
}
//GO = {
// b:1
// }
// AO = {
// a:undefined -> 1
// }
//结果为ƒ a() {} undefined 因为赋值没执行
var b = 3
console.log(a);
function a(a) {
console.log(a);
var a = 2
console.log(a);
function a() {
var b = 5
console.log(b);
}
}
a(1)
//GO = {
// b: undefined -> 3
// a: undefined -> function a(a) {..}
// }
// AO = {
// a:undefined -> function a() {}
// b:undefined ->5
// }
//结果为function a(a) {...}、function a() {}、2、5
a = 1
function test() {
console.log(a);
a = 2
console.log(a);
var a = 3
console.log(a);
}
test()
var a;
//GO = {
// a: undefined ->1
// test:function test() {}
// }
// AO = {
// a:undefined -> 2 -> 3
// }
//结果为undefined、2、3
function test() {
console.log(b);
if(a) {
var b = 2
}
c = 3
console.log(c);
}
var a
test()
a = 1
console.log(a);
//GO = {
// test:function test() {}
// a: undefined -> 1
// c:undefined -> 3
// }
// AO = {
// b:undefined
// }
//结果为undefined、3、1 预编译的时候if里的b也要放进去 不管if。c没有var 所以在GO