2013-07-22 46 views
0

我有這樣的代碼:名稱衝突,並關閉在javascript

function outside() { 
    var x = 10; 
    function inside(x) { 
     return x; 
    } 
    return inside; 
} 
result = outside()(20); // returns 20 instead of 10 

爲什麼函數返回的10 20,而不是爲什麼我不能沒有調用,而不是外部,外部(20)的outdise函數()( 2); why()?

+9

你寫了一本功能離子返回傳遞給它的值。 – thatidiotguy

+2

因爲JavaScript首先解析了更多的局部變量。 –

+0

對於問題的第二部分,'outside()'將返回一個函數對象,但不會調用該函數。 – Dan455

回答

1

這是一個非常「homeworky」的問題,但...

以下是完全一樣的,你寫的東西:

var inside = function (x) { return x } 
var outside = function() { 
    var x = 10; 
    return inside; 
} 

通過函數調用步進:var result = outside()(20),我們看到,這是完全相同的

var result = outside(); // result == inside 
result(20);    // same as calling inside(20), which returns 20. 
0

當您引用變量名時,JavaScript將嘗試從最本地範圍開始解析引用。在這種情況下:

function outside() { 
    var x = 10; // This is the second most local 
    function inside(x) { // The x variable here is the most local 
     return x; // x will be the most local variable named x, ie the parameter 
    } 
    return inside; 
} 

你會得到任何你傳遞給inside()函數。現在,如果你有這個

function outside() { 
    var x = 10; // This is now the most local 
    function inside(y) { // Renamed the parameter to y 
     return x; // returns the variable x 
    } 
    return inside; 
} 

然後你會得到10,爲y參數不再與outside()函數內x變量干擾。即使outside()函數通過名爲關閉的機制退出後,x的值也將保持不變。

現在想象一下,你有:

var x = 5; // This is a global variable 
function outside() { 
    var x = 10; // This is the most local 
    function inside(y) { 
     return x; // x here will refer to the x with a value of 10 
    } 
    return inside; 
} 

在這種情況下,你也將得到10,爲outside()函數內部的x變量更多的本地高於全球x變量。

至於你的函數調用:

result = outside()(20); 

表達outside()調用函數outside,它返回一個參考作用inside()

return inside; // Inside is a function, we're not calling it because there are no parens 

然後,您就調用那函數你有一個參考(即,inside函數),並傳入參數值20.如果雙重pamentalhesis混淆,你可以想到它是這樣的:

var foo = outside(); // foo is a reference to a function 
result = foo(20); // We're now calling that function, passing in 20 as the parameter 

inside()函數返回的20該值時,被設置爲可變result

0

爲什麼函數返回20,而不是10

當有命名衝突的範圍內優先。

爲什麼我不能用外部(20)而不是外部()(2)調用outdise函數;爲什麼()?

調用outside()返回一個函數(正如你可以從return inner看到的那樣)。然後調用該函數。如果您打電話給outside(20),它仍會返回內部函數。如果展開這一點,它可能會更清楚:

var outResult = outside(); // outside returns `inner`, the variable now contains that function 

outResult(20); // call the inner function passing the value 20 
+0

所以如果我理解正確的話: outside()和outside(2)是一樣的嗎? 和返回的函數(內部),我用(x = 20)調用,而不是outResult中的「x」? (即10) – omryk

+1

'outside()'與'outside(2)'具有相同的結果,僅僅是因爲'outside'對傳遞給它的參數沒有任何作用。 –