Joo Park
Joo Park

Reputation: 3145

JavaScript Closures and Memory Leaks

I read in Jquery in Action that memory leaks can result from javascript closures.

"Unintended closures can have unintended consequences. For example, circular references can lead to memory leaks. A classic example of this is the creation of DOM elements that refer back to closure variables, preventing those variables from being reclaimed."

could somebody give an example of this?

thank you!

Upvotes: 4

Views: 3485

Answers (2)

Chadwick
Chadwick

Reputation: 12663

Here, onClick has a closure which keeps reference to element. By assigning onClick to element.click the circle is created: element -> onClick -> element -> onClick...

function addClickHandler(element) {
    element.click = function onClick(e) {
        alert("Clicked the " + element.nodeName)
    }
}

In some (most? certainly not all) javascript engines the garbage collector will not collect an object that has even a single reference to it. Even if element is removed from the DOM, the circular self-reference above would prevent element and onClick from being collected, thus the memory leak.

Upvotes: 2

olliej
olliej

Reputation: 36793

The specific issue is event handlers in IE. Basically if you make an event handler than captures the node it is attached to inside its scope chain then IE will never collect either of them. This is a bug in IE due to its use of refcounting rather than pure GC for liveness.

Upvotes: 0

Related Questions