Where are variables in a closure stored

Like the following codes:

var foo = function() {
    var a = 1; // closure var
    return function() { // closure fun
        console.log(a);
    }
};
var bar = foo();

When foo exits(or say, returns), we know that the variable a will not be destroyed and remains in memory(that's why closure works). So my problem is where does the the variable a store, stack or heap?


A closure is just an evolution of the concept of the stack.

The stack is used to separate/isolate scope when functions are called. When a function returns the stack frame (activation record) is popped off the call stack thus freeing the used memory allowing the next function call to reuse that RAM for its stack frame.

What a closure does is that instead of actually freeing that stack frame, if there's any object/variable in that stack frame that's referenced by anything else then it keeps that stack frame for future use.

Most languages implement this by implementing the stack as a linked list or hash table instead of a flat array. That way, the stack can be re-ordered at runtime and is not constrained by physical memory layout.

So. With this in mind, the answer is that variables in a closure are stored in the stack and heap. Depending on your point of view.

From the point of view of the language, it's definitely the stack. Since that's what closures are in theory - a modified stack.

From the point of view of the machine language or underlying C/assembly code, the idea of a linked-list stack is nonsense. Therefore the higher level language must be using the heap to implement its "stack".

So the variable is in the stack but that stack is probably located in the heap.

This of course depends on the implementation of your programming language. But the above description is valid for most javascript interpreters (certainly all the ones I've seen).

链接地址: http://www.djcxy.com/p/14776.html

上一篇: switch语句中有多个case

下一篇: 封闭中的变量存储在哪里