I understand that a closure is defined as:
[A] stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!)
But I do not understand how this answer fits in the context of JavaScript's storage mechanism. How does the interpreter keep track of these values? Is the browser's storage mechanism segmented in a way similar to the Heap and Stack?
An answer on this question: How do JavaScript closures work? Explains that:
[A] function reference also has a secret reference to the closure
What is the underlying mechanism behind this mysterious "secret reference?"
EDIT Many have said that this is implementation dependent, so for the sake of simplicity, please provide an explanation in the context of a particular implementation.
This is a section of slebetman's answer to the question javascript can't access private properties that answers your question very well.
Here is an example of how you can transform code that needs closures into code that doesn't. The essential points to pay attention to are: how function declarations are transformed, how function calls are transformed, and how accesses to local variables that have been moved to the heap are transformed.
Input:
Output:
Let's break down how the three key transformations go. For the function declaration case, assume for concreteness that we have a function of two arguments
x
andy
and one local variablez
, andx
andz
can escape the stack frame and so need to be moved to the heap. Because of hoisting we may assume thatz
is declared at the beginning of the function.Input:
Output:
That's the tricky part. The rest of the transformation just consists in using
call
to call the function and replacing accesses to the variables moved to the heap with lookups in envs.A couple of caveats.
How did we know that
x
andz
needed to be moved to the heap but noty
? Answer: the simplest (but possibly not optimal) thing is to just move anything to the heap that is referenced in an enclosed function body.The implementation I have given leaks a ton of memory and requires function calls to access access local variables moved to the heap instead of inlining that. A real implementation wouldn't do these things.
Finally, user3856986 posted an answer that makes some different assumptions than mine, so let's compare it.
The main difference is that I assumed that local variables would be kept on a traditional stack, while user3856986's answer only makes sense if the stack will be implemented as some kind of structure on the heap (but he or she is not very explicit about this requirement). A heap implementation like this can work, though it will put more load on the allocator and GC since you have to allocate and collect stack frames on the heap. With modern GC technology, this can be more efficient than you might think, but I believe that the commonly used VMs do use traditional stacks.
Also, something left vague in user3856986's answer is how the closure gets a reference to the relevant stack frame. In my code, this happens when the
envs
property is set on the closure while that stack frame is executing.Finally, user3856986 writes, "All variables in b() become local variables to c() and nothing else. The function that called c() has no access to them." This is a little misleading. Given a reference to the closure
c
, the only thing that stops one from getting access to the closed variables from the call tob
is the type system. One could certainly access these variables from assembly (otherwise, how couldc
access them?). On the other hand, as for the true local variables ofc
, it doesn't even make sense to ask if you can get access to them until some particular invocation ofc
has been specified (and if we consider some particular call, by the time control gets back to the caller, the information stored in them might already have been destroyed).I've written an article on this topic: How do JavaScript closures work under the hood: the illustrated explanation.
To understand the subject, we need to know how scope objects (or
LexicalEnvironment
s) are allocated, used and deleted. This understanding is a key to having a big picture and to know how do closures work under the hood.I'm not going to re-type the whole article here, but as a short example, consider this script:
When executing the top-level code, we have the following arrangement of scope objects:
Notice that
myFunc
references both:And when
myFunc()
is called, we have the following scope chain:When function is called, new scope object is created and used to augment the scope chain referenced by the
myFunc
. It allows us to achieve very powerful effect when we define some inner function, and then call it outside of the outer function.See the aforementioned article, it explains things in detail.