Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading