2

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?

millimoose
  • 39,073
  • 9
  • 82
  • 134
quuxbazer
  • 541
  • 1
  • 4
  • 8
  • Go grab a bottle of vodka and read this question. I'd try to give you an answer but my office has a no alcohol policy. http://stackoverflow.com/questions/500431/javascript-variable-scope – aehiilrs Feb 02 '12 at 21:10

3 Answers3

3

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 setTimeout is created can be referenced long after test2 has 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).

Community
  • 1
  • 1
Wayne
  • 59,728
  • 15
  • 131
  • 126
  • 1
    Thanks! I didn't know there was actually a name for this. You would think that in my 4 years as a computer science undergraduate, they would have as least mentioned this. – quuxbazer Feb 02 '12 at 21:22
1

This occurs due to Javascript Closures. Essentially, variables available to a function at the time it is defined will always be available to it, no matter where it is called from.

Community
  • 1
  • 1
driangle
  • 11,601
  • 5
  • 47
  • 54
0

The feature is called closures. You're basically right about what happens, the variables from the surrounding scope get saved if they're needed in an anonymous function.

millimoose
  • 39,073
  • 9
  • 82
  • 134