Javascript 果然存在所谓的预编译,例证:

1.变量预编译:

Js代码  收藏代码
  1. var test_a = 'a test';  
  2.   
  3. function test1(){  
  4.         alert(test_a);  
  5. }  
  6.   
  7. function test2(){  
  8.         alert(test_a);  
  9.         var test_a = "a test in function";  
  10.         alert(test_a);  
  11. }  
  12.   
  13. test1();  
  14. test2();  

结果 :[a test] [undefined] [a test in function];

个人理解(也参照了网上的很多解释):

浏览器在执行一个作用域内的javascript代码时,会预先将以var定义的变量标记为已定义(相当于在该作用域内注册),并“赋初值:undefined”;

执行代码时遇到变量引用,会先定位作用域内已经定义的变量,若找到则使用该变量(在test2中test_a已经被预定义了,所以可以找到,则会输出其值 ——undefined),若找不到则向父作用域定位变量,一直到window作用域,假如一直到最后都未找到该变量,那么程序到此会报错,说“变量未定义”;

可以再试试下面的代码,以便加深理解:

Js代码  收藏代码
  1. function test1(){  
  2.         alert(test_a);  
  3.     test_a = "a test in function test1";  
  4.     alert(test_a);  
  5. }  
  6.   
  7. function test2(){  
  8.         alert(test_a);  
  9.         var test_a = "a test in function";  
  10.         alert(test_a);  
  11. }  
  12. test1();  
  13. test2();  
  14. alert(test_a);  
  15. var test_a = 'a test';  
  16. // test_a = 'a test'; 试着去掉该句注释,然后将上一句注释掉看看会怎么样  

2.函数预编译:

Js代码  收藏代码
  1. myfunc();  
  2. function myfunc() {  
  3.     alert("myfunc for the first time");  
  4.     return false;  
  5. }  
  6. myfunc();  
  7.   
  8. myfunc = function() {  
  9.     alert("myfunc for the second time");  
  10.     return false;  
  11. }  
  12. myfunc();  
  13.   
  14. function myfunc() {  
  15.     alert("myfunc for the third time");  
  16.     return false;  
  17. }  
  18. myfunc();  
Js代码  收藏代码
  1. alert(myfunc);  

 结果

[myfunc for the third time]

[myfunc for the third time]

[myfunc for the second time]

[myfunc for the second time]

[function () { alert("myfunc for the second time"); return false; }]

个人理解(也参照了网上的很多解释):

暂时只讨论一个作用域内平级的函数块(不同作用域也不会产生重名)。浏览器在执行一个作用域内代码时,也会预先对function fun(){}形式的函数进行“预编译”,并且对于重名的函数,只保留其最后一次的定义的代码逻辑。执行过程中将不再对function fun(){}形式定义的同名函数的逻辑进行重写,但是遇到fun=function(){}这样形式的重名函数,浏览器又会重写fun函数中的代码逻辑(真是怪哉 )。

并且,和变量一样,函数形如var func = function(){}的,在预编译中也会被“注册”到本作用域的已定义变量中,并且初值赋为“undefined”,所以这样定义的函数不能在赋值之前这样执行func(),否则会报错:"func is not a function",因为正式赋值之前浏览器就将它看做一个普通变量(初值为undefined)

原文地址:https://www.cnblogs.com/shihao/p/2219201.html