On 28/07/2005 11:48, Robert wrote:
Do I understand correctly from
http://jibbering.com/faq/faq_notes/closures.html that the following will
create a memory leak in IE?
function createMemoryLeak(id)
{
var el = document.getElementById(id);
el.onclick = function()
{
return false;
}
}
Yes. The element, el, has a property, onclick, which is a function
reference. In the scope chain of that function exists a reference to the
same element, so you now have a loop. The simple fix is to assign null
to el once the listener assignment is complete.
If, for some reason, you needed to keep a reference to el, you would
need to break the loop when the unload event is dispatched. For instance:
var global = this;
function avoidMemoryLeak(id) {
var el;
if(document.getElementById) {
el = document.getElementById(id);
}
if(el) {
el.onclick = function() {
return false;
};
global.onunload = function() {
el = global.onunload
= null;
};
}
}
But, here you wouldn't need to worry as the this operator could be used
within the listener, rather than el.
If you'd end up producing many closure instances where memory leaks may
occur (which could simply mean calling avoidMemoryLeak several times),
then this becomes unmanageable in its current state. Richard Cornford
has produced code that can help in this regard:
<URL:http://www.litotes.demon.co.uk/example_scripts/finalizer.html>
Mike
--
Michael Winter
Prefix subject with [News] before replying by e-mail.