好像3有些存儲在「裏面」的第二呼叫過程中的作用與5增加了它,並返回8
權。每個呼叫outside
創建一個新的inside
函數,並且該函數具有綁定到它的呼叫到outside
的數據。它「關閉」了這些數據。這些被稱爲「封閉」。不要讓名字打擾你,closures are not complicated。
第二次調用outside(outside(3)(5))如何返回值(8)而不是第一次調用的內部函數(內部)?
第二次調用outside
確實返回一個功能(由該調用生成的inside
功能);但是隨後你會立即用第二對()
調用該函數。
線
outside(3)(5);
...打破了這樣的:
var f = outside(3); // Create and get the `inside` function bound to 3
f(5); // Call it, passing in `5`
從您的評論:
那麼你的意思是,在第一致電outside(3)
,'返回'inside
方法od定義變成(改爲?)返回3 + y;
。是對的嗎?
關閉,但不完全。 x
的值不會被燒入inside
; inside
有創建它的上下文的引用,並且該上下文使它可以訪問x
參數。這些都是不太一樣的東西,因爲我們可以看到,如果我們更新了示例位(與溝的數學,這只是掩蓋的東西):
function outside(name) {
// 'inside' uses the 'name' argument from the call to 'outside' that created it
function inside() {
return name;
}
// 'changer' *changes* the 'name' argument's value
function makeCaps() {
name = name.toUpperCase();
}
// Return both of them
return {
inside: inside,
makeCaps: makeCaps
};
}
var funcs = outside("foo");
funcs.inside(); // "foo", because 'inside' uses the 'name' created
// by the call to 'outside', and that 'name' is
// currently "foo"
funcs.makeCaps(); // Changes that same 'name'
funcs.inside(); // "FOO", because that 'name' has been changed
這是關鍵要了解這兩個inside
和changer
關過相同上下文,這是創建它們的調用outside
的上下文。
這也是關鍵要明白,一個新的環境和新的功能是由每個調用創建outside
:
var funcs1 = outside("foo");
var funcs2 = outside("separate");
funcs1.inside(); // "foo"
funcs2.inside(); // "separate"
funcs1.makeCaps();
funcs1.inside(); // "FOO"
funcs2.inside(); // "separate"
@elclanrs也許吧。但我甚至不知道OP在這裏有什麼問題......它可能是*「函數如何存儲在變量中?」或*「變量如何工作?」...... –