首先js的执行过程会先扫描一下整体语法语句,如果存在语法错误,那么直接报错,程序停止执行,没有错误的话,开始从上到下解释一行执行一行,而预解析发生在执行代码语句之前。
PS :个人理解,如果有错误,纯属正常,欢迎大神指正。
函数预解析过程
① 创建一个AO对象(activation object)
② 找形参和变量声明的名 ,作为AO对象的属性名(初始都为undefined)
③ 将实参的值与形参的值相统一
④ 找函数声明,并把属性值写全。如果有与②中重复的属性名,则不写属性名,直接覆盖②的属性值。
案例一
<script>
function f(a) {
console.log(a);
var a = 123;
console.log(a);
function a() {}
console.log(a);
var b = function() {}
console.log(b);
function d() {}
}
f(1);
</script>
案例一解析
-
创建一个AO对象
AO{}
-
找形参和变量声明的名 ,作为AO对象的属性名
AO{ a : undefined, b : undefined }
-
将实参的值与形参的值相统一
a : 1 b : undefined }
-
找函数声明,并把属性值写全。如果有与②中重复的属性名,则不写属性名,直接覆盖②的属性值。
AO{ a : function() {}, // 函数a覆盖变量a b : undefined, d : function d() {} }
执行代码:
下面就是一行一行执行,被提升过的代码句就略过,需要的变量就查看AO对象里的值
<script>
function f(a) {
console.log(a); // function a() {}
var a = 123; // a --> 123
console.log(a); // 123
function a() {}
console.log(a); // 123
var b = function() {} // b --> function () {}
console.log(b); // function() {}
function d() {}
}
f(1);
</script>
———————————————————————————————————
全局预编译
(全局)预编译分三个步骤:
① 生成GO对象 GO{}(global object) 这个GO就是window
② 将全局的变量声明(的名)储存一GO对象中,value为undefinde
③ 将全局的函数声明的函数名作为go对象中的key,函数整体内容为value储存到go对象中
<script>
global = 100;
function fn() {
console.log(global); // undefined
global = 200;
console.log(global); // 200
var global = 300;
}
fn();
var global;
</script>
GO{
// 全局编译,把所有的变量放进来
global : 100
fn : function fn() {
// 在fn函数内部生成自己的AO对象
AO{
global : 300
}
}
}
案例二
<script>
function test(a,b) {
console.log(a);
c = 0;
var c;
a = 3;
b = 2;
console.log(b);
function b() {}
function d() {}
console.log(b);
}
test(1);
</script>
案例二解析
-
创建一个AO对象
AO{}
-
找形参和变量声明的名 ,作为AO对象的属性名
AO{ a : undefined, b : undefined, c : undefined }
-
将实参的值与形参的值相统一
a : 1 b : undefined, c : undefined }
-
找函数声明,并把属性值写全。如果有与②中重复的属性名,则不写属性名,直接覆盖②的属性值。
AO{ a : 1, b : function () {}, c : undefined, d : function () {} }
执行代码:
下面就是一行一行执行,被提升过的代码句就略过,需要的变量就查看AO对象里的值
<script>
function test(a,b) {
console.log(a); // 1
c = 0; // c --> 0
var c;
a = 3; // a --> 3
b = 2; // b --> 2
console.log(b); // 2
function b() {}
function d() {}
console.log(b); // 2
}
test(1);
</script>
案例三
<script>
function test(a,b) {
console.log(a);
console.log(b);
var b = 234;
console.log(b);
a = 123;
console.log(a);
function a() {}
var a;
b = 234;
var b = function() {}
console.log(a);
console.log(b);
}
test(1);
</script>
答案
ƒ a() {}
undefined
234
123
123
ƒ () {}