js运行三部曲
- 语法分析
- 预编译
- 解释执行
//语法分析-->通篇扫描看有没有语法错误
//预编译
预编译前奏
1.imply global暗示全局变量:即任何变量,如果变量未经声明就赋值,此变量就为全局对象所有。- eg: a = 123;
- eg: var a = b = 123;
- eg: var a = 123; ===> window.a = 123;
预编译
四部曲
- 创建AO对象 (Activation object)(执行期上下文)
- 找形参和变量声明,将变量和形参名作为AO的属性名,值为undefined
- 将实参值和形参统一
- 在函数体里面找函数声明,值赋予函数体
//预编译发生在函数执行的前一刻
function test(a, b) {
console.log(a);//1
c = 0;
var c;
a = 3;
b = 2;
console.log(b);//2
function b () {}
function d () {}
console.log(b);//2
}
test(1);
AO {
a : 1,
b : function b () {},
c : undefined,
d : function d () {}
}
function test(a, b) {
console.log(a);//fn
console.log(b);//undefined
var b = 234;
console.log(b);//234
a = 123;
console.log(a);//123
function a() {}
var a;
b = 234;
var b = function () {}
console.log(a);//123
console.log(b);//fn
}
test(1);
//全局执行期上下文,生成一个GO 对象 Global Object
//GO {
// a : 123,
//}
//GO === window
var a = 123;
function a() {}
console.log(window.a);
console.log(a);
console.log(test);//fn
function test(test) {
console.log(test);//fn
var test = 234;
console.log(test);//234
function test() {
}
}
test(1);
var test = 123;
var global = 100;
function fn() {
console.log(global);//100
}
fn();
global = 100;
function fn() {
console.log(global);//undefined
global = 200;
console.log(global);//200
var global = 300;
}
fn();
var global;
function test() {
console.log(b);//undefined
if(a) {
var b = 100;
}
console.log(b);//undefined
c = 234;
console.log(c);//234
}
var a;
test();
a = 10;
console.log(c);//234
function bar() {
return foo;
foo = 10;
function foo() {
}
var foo = 11;
}
console.log(bar());//fn
console.log(bar());//11
function bar() {
foo = 10;
function foo() {
}
var foo = 11;
return foo;
}
(window.foo || (window.foo = 'bar'));//'bar',先算括号内