最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Where are variables in a closure stored - stack or heap? - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question edited Jun 15, 2021 at 9:57 trincot 350k36 gold badges271 silver badges322 bronze badges asked Mar 24, 2015 at 5:48 JunGorJunGor 4434 silver badges10 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 41

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).

发布评论

评论列表(0)

  1. 暂无评论