js预编译和解析

(1)http://bbs.csdn.net/topics/370190620

两段代码的比较:

<script type="text/javascript">
 f ( );
 function f(  ){
  alert(1);
 }
  </script>

程序运行的结果是:弹出数字“1”

<script type="text/javascript">
 f ( );
 var f=function (  ){
  alert(1);
 }
  </script>

程序运行会发生错误,缺少对象。。

 

(2)

再来段代码比较:

<script type="text/javascript">
 function hello(  ){
  alert("hello");
 }
 hello(  );
 function hello(  ){
  alert("hello world");
 }
 hello(  );
  </script>

连续弹出2个hello world,而非先hello,后hello world 


<script type="text/javascript">
 function hello(  ){
  alert("hello");
 }
 hello(  );
 var hello=function(  ){
  alert("hello world");
 }
 hello(  );
  </script>

连续先弹出hello,后弹出hello world 

<script type="text/javascript">
  var hello=function (  ){
 alert("hello");
  }
  hello(  );
  function hello(  ){
    alert("hello world");
  }
  hello(  );
  </script>

连续弹出2个hello

 

 

对其中一个例子进行的详解:

<script type="text/javascript">
var hello=function (  ){
alert("hello");
}
hello(  );
function hello(  ){
alert("hello world");
}
hello(  );
  </script>

第一步扫描var关键字,提前到最顶端: 
var hello;
第二步扫描function定义式,提到var之后:
var hello;
function hello(){
  alert('hello world');
}
第三步顺序执行代码:最终如下:
var hello;
function hello(){
  alert('hello world');
}
hello = function(){
alert('hello');
}
hello(); // 弹hello
hello();//弹hello

2)http://bbs.csdn.net/topics/390292030

大概说说js的解析顺序,js引擎读取一段js代码,首先预解析(这个名字我起的),就是逐行读取js代码,寻找全局变量和全局函数,遇到全局变量,把变量的值变为undefind,存在内存中,遇到全局函数,直接存在内存中,这个过程如果发现语法错误,预解析终止。
我们平时遇到这种情况:
alert(a)  
var a=100
这个弹出undefind,而不是没有这个变量的语法错误,就是因为预解析时候把a调成了undefind存在内存中,
还有下面我们之所以可以先调用f1,后定义f1函数,也是因为预解析,f1已经存在内存中。
f1()
function f1(){ return 123}

当预解析完成后,js引擎在从第一行开始逐行运行js代码。
知道这个对于理解函数作用域能提供些帮助。

3)http://blog.csdn.net/yingyiledi/article/details/25634607

4)http://www.cnblogs.com/xiziyin/archive/2010/05/02/1705115.html

1.js在页面加载过程中顺序执行。但是分块预编译、执行。 
2.JS 在执行前会进行类似"预编译"的操作,而且先预声明变量再预定义函数。 
此时注意,是声明,不是定义,如:var a = 1; 在预编译中,只是执行了"var a"没有赋值,即在预编译结束时a 为undefined。 
3.(注意)并不是先全文编译完在执行,而是块编译,即一个script块中,预编译再执行,然后(按顺序)下一个script块,预编译再执行,但此时上一个块中的数据都是可以用的,但下一个块中的函数,声明的变量都是不可用的。 
4.变量没声明就引用,会报错,但对象方法,对象变量没声明,是undefined 
5.在函数中变量不声明就赋值,会被认为是全局变量,用var声明后为函数变量 
6.在执行函数时时也是先编译后执行,但要注意函数定义中(即大括号中)的代码即使有错只要函数不执行,就不会有影响,但一执行函数,开始函数预编译就会出错。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值