在维基百科(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