Assigning local reference to global

here’s what I can’t understand.

I have this function here

function foo(){
let a = {a:1};
window.a = a; 
}

as you can see, this assign to a an object, so a reference to it, and then it creates a new property on the window object that contains this reference. If the a variable is local, it’s reference point to an address in the stack, so, how can I access a from window, also out of the function, when the stack is cleaned?

>Solution :

If the a variable is local, it’s reference point to an address in the stack

No. While a variable might be allocated on a stack containing the reference, what it references (the object) is likely allocated on "the heap", as – as you’ve noticed – it’s lifetime is not known and as such must be managed by the garbage collector and cannot be stack-allocated.

That said the "stack" vs. "heap" distinction is not quite reflecting the reality of modern JIT-compilers.

Leave a Reply