Skip to main content

Posts

Showing posts from September, 2005

JavaScript: JavaScript has Closures

Python has closures: def outer(): print "Enter number:", num = raw_input() def inner(): print num return inner f = outer() f() 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); } testSetTimeout(); 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.