Quote from
Google JavaScript style guide :
The ability to create closures is the most useful and often overlooked feature of JS.
However, one thing needs to be kept in mind: a closure stores a pointer to the context that it closes. As a result, attaching a closure to a DOM element can cause cyclic dependency and, therefore, memory leakage. For example, in the following piece of code:
')
function foo(element, a, b) { element.onclick = function() { }; }
a closure stores a pointer to
element
,
a
and
b
even if it never uses
element
. And since
element
also stores a pointer to the closure, it turns out a cycle that will never be cleaned by the garbage collector.
In such cases, the code should be structured as follows:
function foo(element, a, b) { element.onclick = bar(a, b); } function bar(a, b) { return function() { } }
It seems that at the moment this is the most common practical example of a memory leak in JavaScript.