112 Part I: Core Ideas
Closures and Memory Leaks
Internet Explorer has a problem freeing memory and closures when there are circular
references. A circular reference is when one object has a pointer that points to another object
and that object creates a reference back to the first. There are other ways to make such a
cycle, of course, but the place that we most often see circular references is in event handlers
where the event-handling function references the bound node that the event was triggered
upon. For example, a mouse click against a particular form element references a function
that then references back to that particular form element that the event was captured upon.
The example here creates the number of <div> tags you specify, with event handlers
referencing each.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Chapter 3 : Memory Leak Tester</title>
<script type="text/javascript" language="javascript">
function createDivs()
{
var countSpan = document.getElementById("countSpan");
var numDivs = document.requestForm.numberDivs.value;
var oldNumDivs = parseInt(countSpan.innerHTML,10);
var newNumDivs = oldNumDivs + parseInt(numDivs,10);
if (newNumDivs > 0)
{
for (var i=oldNumDivs; i<newNumDivs; i++)
{
createClosure(i);
}
countSpan.innerHTML = newNumDivs;
}
}
function createClosure(i)
{
var div = document.createElement("div");
div.id = "leakydiv" + i;
div.onclick = function() { this.innerHTML = "Clicked"; };
document.body.appendChild(div);
}
window.onload = function ()
{
document.requestForm.requestButton.onclick = createDivs;
};
</script>
</head>
<body>
<form action="#" name="requestForm">
Number of Divs: <input type="text" name="numberDivs" />
<input type="button" name="requestButton" value="Make Leaky Div(s)" />