當您引用變量名時,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
。
你寫了一本功能離子返回傳遞給它的值。 – thatidiotguy
因爲JavaScript首先解析了更多的局部變量。 –
對於問題的第二部分,'outside()'將返回一個函數對象,但不會調用該函數。 – Dan455