What Happens With Values In Closure? Javascript
I've seen a really cool explanation of closure. So in my view closure is a way to store data somewhere. Let's see examples of closure and example without closure: Without closure:
Solution 1:
Every time you call a function, a new activation context containing the local variables is created. If inner functions use any of those variables, the activation context is saved (in a closure) so the local variables can be accessed outside of that function.
There is only one closure created per activation context (function call). That is,
// One closure is created every time you call doSomething// The loop in doSomething creates a single closure that is shared // by all the divs handlers (or all the handlers point to the same function// instance and its closure)functiondoSomething(divs) {
for (var i =0; i < divs.length; i++) {
div.onclick = function() {
// Because there is only one closure, i will be the same// for all divsconsole.log('Clicked div, i is' + i);
}
}
}
// One closure heredoSomething([div1,div2,div3]);
// One closure heredoSomething([div9,div10, div11]);
The garbage collector will never garbage collect a closure that still has references to it. As an aside, this was one of the sources for memory leaks. There's often a circular reference between a closure and a DOM element, which kept IE from garbage collecting that closure because it couldn't detect that circular reference between DOM elements and regular JavaScript objects.
Post a Comment for "What Happens With Values In Closure? Javascript"