(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.在執行函數時時也是先編譯后執行,但要注意函數定義中(即大括號中)的代碼即使有錯只要函數不執行,就不會有影響,但一執行函數,開始函數預編譯就會出錯。