Before I begin, I realize that the ECMA script specification will probably answer my question, but I am asking it on SO in hope of a comprehensible answer.
Take the following code:
function test1(param) {
alert(param);
}
function test2() {
var testvar = 99;
setTimeout(function(){ test1(testvar); }, 1000);
}
test2();
If I run this code, I get a popup box showing 99.
My question is, in test2, shouldn’t testvar be null after test2 finishes running? How does the anonymous function in setTimeout get the value of testvar? Is there some sort of stack copying going on right as setTimeout gets called?
This is the result of closures. Functions in JavaScript retain references to — “close over” — variables defined in their lexical scope. That is, all variables that can be referenced when the function given to
setTimeoutis created can be referenced long aftertest2has returned.In this way, a closure is both a function and a set of bindings to the variables that were in scope when the function was created. This is why closures are sometimes called poor man’s objects (and vice versa).