https://stackoverflow.com/questions/2800463/how-variables-are-allocated-memory-in-javascript
https://stackoverflow.com/questions/1026495/does-javascript-have-a-memory-heap
When you call a function, amongst other things a variable environment for that call is created, which has something called a “variable object”.
The “variable object” has properties for the
– arguments to the function
– all local variables declared in the function
– and all functions declared within the function (along with a couple of other things)
When a closure survives the function returning (which can happen for several reasons), the variable object for that function call is retained in memory (heap) by the reference from the closure.
At first glance, that would suggest that the stack isn’t used for local variables; in fact, modern JavaScript engines are quite smart, and may (if it’s worthwhile) use the stack for locals that aren’t actually used by the closure. (Naturally, the stack is still used for keeping track of return addresses and such.)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
function foo(a, b) { var c; // property c console.log("a: " + a) console.log("b: " + b) c = a + b; console.log("c: " + c) // closure function bar(d) { // can access foo's property c console.log("d * c = " + (d * c)); } return bar; } var b = foo(1, 2); b(3); // logs "d * c = 9" |
Due to our function bar (which is a closure) uses and references c, if our function call ends and pops, our closure bar is still chained to “foo”, and thus be able to use c. Depending on the js engine, it may then move “c”
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
+----------------------------+ | `foo` call variable object | | -------------------------- | | a = 1 | | b = 2 | | c = 3 | | bar = (function) | +----------------------------+ ^ | chain | +----------------------------+ | `bar` call variable object | | -------------------------- | | d = 3 | +----------------------------+ |