Closures and memory leaks

J

Jeremy

I'm looking for a some tips on what circumstances cause a closure to
produce a memory leak.

For example, let's say I have a constructor that adds event listeners to
a DOM node:

function Goober(domNode)
{
this.domNode = domNode;
this.foo = 12;
domNode.onclick = function() { alert('Bing!'); };
}

Now let's say I want to access the Goober instance from the event
handler, so I create a closure to make 'this' of the constructor
available to the event handler:

function Goober(domNode)
{
this.domNode = domNode;
this.foo = 12;
var meGoober = this; //folly?

domNode.onclick = function() { alert(meGoober.foo); };
}

Have I just caused a memory leak? Have I made a cyclical reference by
virtue of the fact that meGoober references this, whose domNode property
has an eventHandler that references meGoober?

It's easy to understand what a closure is and when it's useful, but
understanding their pitfalls is considerably more difficult. Anyone
have a good read for this?

Thanks,
Jeremy
 
R

Richard Cornford

Jeremy said:
I'm looking for a some tips on what circumstances cause
a closure to produce a memory leak.

For example, let's say I have a constructor that adds event
listeners to a DOM node:

function Goober(domNode)
{
this.domNode = domNode;
this.foo = 12;
domNode.onclick = function() { alert('Bing!'); };
}

Now let's say I want to access the Goober instance from the event
handler, so I create a closure to make 'this' of the constructor
available to the event handler:

function Goober(domNode)
{
this.domNode = domNode;
this.foo = 12;
var meGoober = this; //folly?

domNode.onclick = function() { alert(meGoober.foo); };
}

Have I just caused a memory leak?

In IE versions up to 6, yes.
Have I made a cyclical reference by virtue of the fact that meGoober
references this,

Yes, but to finish the circle the Goober object instance must hold on to
a reference to the DOM element, which it does in its - domNode -
property. Avoid that and you don't have a circle and so don't have a
leak.
whose domNode property has an eventHandler that references meGoober?

It's easy to understand what a closure is and when it's
useful, but understanding their pitfalls is considerably
more difficult. Anyone have a good read for this?

A good read would be one that did not attribute the issue to closures
but instead to the circular chains of reference, which can easily be
created without using closures at all.

Richard.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top