JacaScript预解析

(1)什么是js的预解析?
预解析就是js代码在执行之前会在相应的执行环境中预先把一些东西解析到内存。
预解析一般都预先解析哪些东西?
预先解析 function 和 var
预解析的顺序是什么样的?
1、首先是找到<script></script>标签按照<script>块依次解析
2、解析执行环境
3、对标识符(var function)进行解析
例如:
<script>
test();
function test(){
alert('This is test');
};
</script>
在浏览器中打印出来的是This is test
上面的案例中,在function test()之前就调用了test()函数照样可以弹出 This is test 可见在js执行之前就预先把 function test()解析到了内存,所以调用test()照常弹出结果;然而当我们执行了 var test = "this is test";这就话是就完成了赋值,所以在次调用 alert 就弹出 this is test。

(2)变量和函数重名的时候会是什么情况?
例如:
<script>
alret(test);
var test = "this is test";
function test(){
return "this is function";
};
alert(test);
</script>
上面的案例中,当函数名和变量名一样的时候,alert(test);调用的是函数function test()的指针,而不是调用的变量 var test;所以function的预解析 优先级 高于 var 。

(3)"解析执行环境"是什么意思?
<script>
function test(){
var msg = 'This is test';
};
alert(msg); //报错msg未定义
</script>
上面的案例中,为什么会出现msg未定义呢!?预解析不是会在js执行的时候预先解析 function 和 var msg 吗?我们在function里面定义了 var msg,那么为什么会报错呢!?
原因:“解析环境” 在js执行之前是会预解析 function 和 var没错,但是在本例中他们“解析执行环境”不同。
function test 是在一个全局的环境中,而msg是function test 中定义的一个局部变量,msg的“解析执行环境”是在function test 这个函数里面(这里可以理解为function test里的局部环境),所以当我们在全局这个环境中 alert(msg) 的时候,并没有定义msg这个变量或者函数,所以就报错了。
<script>
alert(msg);
function test(){
alert(msg2);
var msg2 = 'This is test';
};
var msg = "123";
test();
</script>
经过修改后的实例中,会弹出两个undefined,第一个是 alert(msg) 运行时弹出的结果,第二个是 alert(msg2) 运行时弹出的结果.
js在执行之前 预解析,解析全局的环境,解析到function test 和 var msg ;所以 alert(msg) ;会弹出undefined;
然后当程序执行到 test() ;的时候会进入 function test 里面去,也就是进入 function test 的局部环境去 预解析 ,这时候解析到 var msg2 ,所以也弹出了undefined ;

(4)变量预解析:
<script>
alert(test);
var test = "this is test";
alert(test);
</script>
上面的案例中,首先弹出的是undefined,然后接着弹出的是 this is test,在 var test = 'this is test',之前就调用 alert 弹出 test ,而没有报 test 未定义的错误,而是弹出了undefined,可见在js执行之前就预先把 var test的定义预先解析到内存里了,但是并没有给变量赋值。

本人菜鸟一枚,如有理解不当之处,欢迎各位留言指正。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章