This article summarizes the memory leak problem of JavaScript in versions before IE9. Friends who are interested in this can learn about it.
Versions before IE9 use different garbage collection routines for JScript objects and COM objects (COM objects use a "reference counting" collection strategy), so closures will cause some special problems in these versions of IE. Specifically, if an HTML element is stored in the scope of the closure, it means that the element cannot be destroyed.
Look at the following example:
function assignHandler() { var elem = document.getElementById('elem_id'); elem.onclick = function(evt) { alert(elem.id); }; }
The above code creates a closure as the elem element event handler, and this closure creates a circular reference. Since the anonymous function saves a reference to the active object of assignHandler(), it will not be possible to reduce the number of elem references. As long as the anonymous function exists, the reference number of elem is at least 1, so the memory it occupies will never be recycled.
The above code can be solved by slightly modifying it:
function assignHandler() { var elem = document.getElementById('elem_id'); var elem_id = elem.id; elem.onclick = function(evt) { alert(elem_id); }; elem = null; }
By saving a copy of elem.id in a variable and referencing it in the closure Variables eliminate circular references. But just doing this step still cannot solve the memory leak problem.
"The closure refers to the entire active object containing the function, which contains elem. Even if the closure does not directly reference elem, a reference will still be saved in the active object containing the function. Therefore, it is necessary Set elem to null. This will dereference the DOM object, successfully reduce its number of references, and ensure normal recycling of the memory it occupies."
Summary: The above is the entire content of this article, I hope it can It will be helpful to everyone’s study. For more related tutorials, please visit JavaScript Video Tutorial!
Related recommendations:
php public welfare training video tutorial
The above is the detailed content of Summarize the memory leak problem of JavaScript in versions before IE9. For more information, please follow other related articles on the PHP Chinese website!