Make delicious recipes!


Closure in JavaScript


A closure in JS is created when

  1. A function is declared inside another function and that inner function has some reference to the parent function’s variables. If such an inner function is returned, then we get a closure.

  2. When eval is called inside a function.


A function declared inside another function has access to all the variables declared in the parent function (even if they were declared after the child function !!)

Now, if a reference to inner function is returned, closure is created.

Closure can loosely be defined as a hidden reference to the stack-frame of parent function call.


Example:



A very important thing to note in the above is that closureFn1 and closureFn2 both have their own copy of the closure. That is because the call stack for both of them was different when parentFn was called.

An equally important corollary of the above is that if two child functions were embedded in a parent function, then both of them would share the same call stack no matter when the parent is called. This means that the two child functions will also share also the variables of the parent function.


So a function reference in JS can behave very differently depending upon the hidden closure reference of the function.

Closures can result in some hard to find memory leaks as shown in following example:


In the above, if the onclick referred to some function outside the scope of parent function, then there would be no memory leak.

But since it refers to something inside the parent function, a closure is created and to make it work correctly, the JS engine has to keep the context of parent function alive.

If the onclick reference was to some external function, then there would have been no need to keep the stack of parent function call as there would have been no reference to its internal variables. But with a live reference to internal function/variable, the stack cannot be garbage collected and it would cause a memory leak.







Like us on Facebook to remain in touch
with the latest in technology and tutorials!


Got a thought to share or found a
bug in the code?
We'd love to hear from you:

Name:
Email: (Your email is not shared with anybody)
Comment:

Facebook comments:

Site Owner: Sachin Goyal