在維基百科(http://en.wikipedia.org/wiki/Closure_(computer_programming))的此示例中,它聲稱調用變量closure1
和closure1(3)
將返回4
。有人可以通過這個例子 - 我不明白。關閉 - 澄清變量和函數
function startAt(x)
function incrementBy(y)
return x + y
return incrementBy
variable closure1 = startAt(1)
variable closure2 = startAt(5)
Invoking the variable closure1 (which is of function type) with closure1(3) will return 4, while invoking closure2(3) will return 8. While closure1 and closure2 are both references to the function incrementBy, the associated environment will bind the identifier x to two distinct variables in the two invocations, leading to different results.
如果有幫助,這是我目前的理解。 variable closure1 = startAt(1)
將變量closure1
設置爲功能startAt()
,其默認初始化爲1
。但是,調用closure1(3)
會將此默認值設置爲3
。我不明白的是y
來自哪裏。
variable closure1 = startAt(1)
相關:[JavaScript關閉如何工作?](http://stackoverflow.com/questions/111102/how-do-javascript-closures-work) – apsillers 2014-11-14 14:49:56
關閉只是可憐的人類。類只是窮人關閉。 – leppie 2014-11-14 15:24:05