Python has closures:
Did you know that JavaScript has them too?
def outer():Note that the variable num is available from within inner when outer has already completed.
print "Enter number:",
num = raw_input()
def inner():
print num
return inner
f = outer()
f()
Did you know that JavaScript has them too?
function 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.
var privateVar = 'A string';
function bar() { alert(privateVar); }
window.setTimeout(bar, 1000);
}
testSetTimeout();
Comments
var accum = function() {
var i = 0;
var get = function() { return i };
var set = function() { i++ };
return [get, set];
}
var x = accum()
x[1]()
x[1]()
x[0]()
The last line will return 2.
dp
def outer():
num = [5]
def inner():
num[0] += 1
print num[0]
return inner
f = outer()
f()
(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.