top | item 3627820

(no title)

narkee | 14 years ago

Thanks for the explanation, closures have been a little tricky for me to wrap my head around.

I'm confused a little with regards to the closure closing over the "value" of free variables, or the reference.

For example, in python:

    i = 1
    def f():
        return i

    i = 2
    def g():
        return i
Both f() and g() return 2, even though when f() is defined, shouldn't i=1 be closed over in this case? That's what I find confusing here, in the sense that the state of the environment changes outside the closure affect things inside the closure.

discuss

order

tkahn6|14 years ago

This is a property of how javascript and python do closures. In the above code i refers to the same piece of memory in every case. So f and g are closed over i. The reference is preserved but the value is not.

This behavior is the motivation behind the do keyword in CoffeeScript.

Here's more on this:

http://stackoverflow.com/questions/233673/lexical-closures-i...