JavaScript closures

There isn’t a huge conspiracy to hide what closures mean to the power of JavaScript, but the principles can be easily understood.

A closure is actually more liberating than the name implies.  It opens the door to new possibilities by passing variables between lower-level functions.

Take for example, a very simple closure:

var ourFunction = function() {
var ourFunction2 = function() { alert(ourVar); };
var ourVar = "A simple JavaScript closure.";

ourFunction2();
};

As you can see, the ourVar variable is available to ourFunction2 despite ourVar being defined in the scope of ourFunction (locally).  Even if ourFunction2 wasn’t defined inside of ourFunction, we’d still have access to ourVar.  Similarly, if ourVar was a parameter of ourFunction, we’d still have access to it within ourFunction2.

Internet Explorer and Circular References

So what is it about closures that give them a bad rap?  The horrible truth is that Internet Explorer is to blame.  A bug in their automatic garbage collection of closures (removing unneeded closures) causes circular references involving DOM nodes or ActiveX objects to not be freed from the memory until the browser closes.  A circular reference is created when 2 or more functions/elements/objects refer back to each other.

document.onload = function() {
var obj = document.getElementById("someDiv");
obj.onclick = function() { alert("Leak"); };
};

The obj variable is referenced, and then a closure is created for the onclick event of obj. This means that the closure will never be cleared, even if document.onload is changed. But there is hope! One solution is to simply set obj to null after creating the closure. This breaks the circular reference by removing one of the objects in that circular reference.

Another solution is to create another closure within the function to prevent the circular reference.

document.onload = function() {
var obj = document.getElementById("someDiv");
(function() { obj.onclick = function() { alert("Leak"); }; })();
};

Or, alternatively, just avoid creating a closure in general.

document.onload = function() {
var obj = document.getElementById("someDiv");
obj.onclick = respondFunc;
};
var respondFunc = function() { alert("No leak"); };

To closure or not to closure?

Any way you look at it, closures are a powerful feature of JavaScript. They enable some really special things to happen in JavaScript that would be much more difficult without the feature.

Share Your Thought