2012-03-08 82 views
0
<html> 
<head> 
<script type='text/javascript'> 
    var process = function (test) { 
     var i = test; 
     this.echo = function() { console.log(i); }; 
    }; 
    var test = 'hai'; 
    var hai = new process(test); 
    hai.echo(); 
    test = 'sorry'; 
    hai.echo(); 
</script> 
</head> 
<body style='height:1000px;width:100%'> 
</body>  

在執行上述測試腳本時,我得到了'對不起'兩次,我希望'海'然後'海'。Javascript變量聲明和範圍

當我改變行5爲[作了隨機試]

var i = (function() {return test;})(); 

我明白了「海」 &「海」

它是如何的情況下工作2 &爲什麼沒有它在情況1?

AFAI,JavaScript並可變起重因爲測試將在範圍的開始被初始化爲未定義和將被重新分配爲,當它被分配的值。但是,這並沒有幫助我。

+2

您的代碼顯示'「hai」'兩次對我來說是不可能的。 – pimvdb 2012-03-08 10:11:38

+1

抱歉沒有注意到我的錯誤投票刪除了我自己的問題 – Tamil 2012-03-08 10:19:12

回答

3

你很容易混淆通過引用通過值。 JavaScript only允許後者(儘管你可能在其他地方閱讀)。

在這種情況下,您將值"hai"傳遞給構造函數process。然後將該值存儲在內部範圍內,變量爲i。之後更改test的值將不會更改i的值。

出於同樣的原因,您的任何測試用例都無法工作。

2

您引用的代碼不像您所描述的那樣運行。但是,試圖反正回答這個問題,這裏是你的代碼有一些內嵌的解釋:

var process = function (test) { 
    var i = test; 

    // Here you're creating a "closure" over the context of 
    // this specific call to this function. So the `i` local 
    // variable lives on, even after this function call 
    // terminates. 
    this.echo = function() { console.log(i); }; 
}; 

// This `test` variable is *completely and totally* unrelated to the 
// `test` argument to your function above. They do not interact in 
// any way. 
var test = 'hai'; 

// Here, yu're passing the *value* of the `test` variable ("hai") 
// into the function. The function has no reference to the `test` 
// variable at all (er, not a relevant way; details below). From 
// the function's point of view, it's *exactly* like 
// `var hai = new process("hai");` 
var hai = new process(test); 

// This will show "hai" 
hai.echo(); 

// This will also show "hai", because again, the `i` in the `echo` 
// function is the local variable in the call to `new process` above; 
// it is in no way whatsoever related to the `test` variable here. 
test = 'sorry'; 
hai.echo(); 

探索更多(在我的博客):Closures are not complicated


細節我注意到有關如何process功能沒有相關test變量的引用:從技術上講,您分配給process的函數確實會引用test變量,因爲它是scop上的閉包e其中定義了test變量。但它不是使用,因爲它有它自己的test參數和該符號陰影(重寫)來自包含範圍的一個。其中沒有任何與你通過test進入調用process函數有關,這就是爲什麼它是不相關的。

0

它會顯示2次海。由於存儲變量i在區域範圍function echoi只設置一次到hai