How do JavaScript closures work under the hood

added by bpwndaddy
9/15/2015 1:07:55 AM

493 Views

I've been using closures for quite some time already. I learned how to use them, but I didn't have clear understanding of how closures actually work, and what's going on behind the scenes when I use them. What the closure is exactly, to begin with? Wikipedia doesn't help very much. When it is created and deleted? What the implementation should look like? "use strict"; var myClosure = (function outerFunction() { var hidden = 1; return { inc: function innerFunction() { return hidden++; } }; }()); myClosure.inc(); // returns 1 myClosure.inc(); // returns 2 myClosure.inc(); // returns 3 // Ok, very nice. But how is it implemented, // and what's going on behind the scenes? And when I eventually got it, I felt excited and decided to explain it: at least, I will definitely not forget it now. You know, Tell me and I forget. Teach me and I remember. Involve me and I learn. © Benjamin Franklin And, after all, while I was reading existing explanations of closures, I tried hard to imagine visually how things relate to each other: which object references others, which one inherits from another, etc. I failed to find such useful illustrations, so, I decided to draw my own. I assume that the reader is already familiar with JavaScript, knows what is a Global Object, knows that functions in JavaScript are “first-class objects”, etc.


0 comments