iT邦幫忙

DAY 5
1

網頁開發五四三系列 第 6

function , script block in JavaScript (函式,腳本區) 3

繼續介紹關於 JavaScript 中的 腳本區 script block....
上上篇文章:http://ithelp.ithome.com.tw/question/10127299

上篇文章:http://ithelp.ithome.com.tw/question/10127586

在上上篇文章,提到 parse-time 與 run-time 的不同

在上篇文章,也說明了,在呼叫變數、函式時,如果在該 script block (腳本區)

呼叫不到時,會向上一層做查詢

本篇文章再繼續延伸進行說明,程式碼&說明如下:

function f1()
{
	alert('outside');
}

console.log('test 1 - ' + f1);

;(function(){

console.log('test 2 - ' + f1);

var f1 = function()
{
	alert('var');
}

console.log('test 3 - ' + f1);
	
})();

console.log('test 4 - ' + f1);

(這一次我們不直接 alert 出結果,而是將資料直接 console 出來檢視)

test 1 - function f1()
{
	alert('outside');
} 
test 2 - undefined 
test 3 - function ()
{
	alert('var');
} 
test 4 - function f1()
{
	alert('outside');
} 

test 1 - 結果是 outside -> 無疑

test 2 - 因為在 line 12 有一個 RunTime 才會宣告的 f1 (巢狀內變數),
因此在 test 2 的 f1 並不會去向上讀取 window.f1
程式碼中在 test 2 的 f1 為 undefined.

test 3 - 因 line 12 ~ 15 , 此時巢狀內的 f1 變數已經有資料 , 為 var

test 4 - 因為巢狀內使用的是 區域變數 ( block var ) 所以並不影響 window.f1 , 所以,結果還是 outside

PS :
在 巢狀(block)內的變數 , 通常在 巢狀一開始,就會被宣告(但並未會使用or給值)
所以,程式在叫用的時候,只會出現 undefind. 但程式繼續執行。
(試圖讀取一個 xxx 從未使用的變數) , 將 line 10 修改為 console.log('test 2 - ' + xxx);
因為xxx連宣告的動作都沒有,則會出現 Uncaught ReferenceError: xxx is not defined 錯誤(而此錯誤會導致程式中斷)


上一篇
搶在天兔來臨前,"硬頸"一下....
下一篇
function , script block in JavaScript (函式,腳本區) 4
系列文
網頁開發五四三12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 則留言

我要留言

立即登入留言