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 created 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.
You can solve the problem by slightly modifying the above code:
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 that variable in the closure eliminates the circular reference. 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. In this way, the reference to the DOM object can be released, the number of references can be reduced smoothly, and the memory occupied by it can be properly recycled. helpful.
Related articles:
JavaScript hasOwnProperty() function (picture and text tutorial, with code examples) In Javascript The for in loop is used in combination with hasOwnPropertyThe difference between using JavaScript isPrototypeOf and hasOwnProperty (practical)
The above is the detailed content of JavaScript memory leak problem in versions before IE9 (detailed summary). For more information, please follow other related articles on the PHP Chinese website!