Tuesday, September 06, 2005

JavaScript: JavaScript has Closures

Python has closures:
def outer():
print "Enter number:",
num = raw_input()
def inner():
print num
return inner

f = outer()
Note that the variable num is available from within inner when outer has already completed.

Did you know that JavaScript has them too?
function testSetTimeout() {
var privateVar = 'A string';
function bar() { alert(privateVar); }
window.setTimeout(bar, 1000);

The function bar makes use of privateVar which a variable in testSetTimeout's local scope even though bar is invoked later by setTimeout, i.e. after testSetTimeout has completed.


Donovan said...

JavaScript even has non-neutered closures, unlike Python. In Python, there is no distinction between creating a name in an inner scope and changing the value stored in that name. JavaScript has the "var" construct (did you know that any variable declared in JavaScript without var is automatically global?) and thus has a way to distinguish between creating a new cell in an inner scope and rebinding an outer cell in a containing scope.

var accum = function() {
var i = 0;
var get = function() { return i };
var set = function() { i++ };
return [get, set];

var x = accum()


The last line will return 2.


Shannon -jj Behrens said...

Nice tip. It makes total sense. My buddy Brandon L. Golm has argued with me many times wishing that Python's global and local variables were at least declared like with "my" in Perl. I guess this is one small case where it would pay off. I've actually encountered this limitation in my code. If you really need to get around it, wrap the variable with a list, and then modify the first element of that list:

def outer():
num = [5]
def inner():
num[0] += 1
print num[0]
return inner

f = outer()

(Ugh, Blogger won't let me use the pre tag to indent things.)

I saw this trick in Sam Rushing's code, so I can't take credit for it.