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
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