In this example on Wikipedia (http://en.wikipedia.org/wiki/Closure_(computer_programming) ) it claims that invoking the variable closure1
with closure1(3)
will return 4
. Can someone walk through the example - I don't understand.
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.
If it helps, here's my current understanding. variable closure1 = startAt(1)
sets the variable closure1
to the function startAt()
which by default is initialized to 1
. However, invoking closure1(3)
sets this default value to 3
. What I don't understand then is where does y
come from.
variable closure1 = startAt(1)