function fors(){
obj_a = obj_b;
obj_b.attr = obj_a;
}
function fors(){
obj_b = {};
obj_b.attr = obj_b;
}
The above are two very obvious circular references. A memory leak occurs in IE. Due to IE's memory recycling mechanism, the memory will be occupied for a long time and cannot be released.
But the memory leak of closure is somewhat hidden. Because the circular reference of the closure is indirect.
function iememery(){
var js_obj = document .createElement("div");
js_obj.oncontextmenu = function(){ return false;}
}
On the surface, there aren't any circular references. But the above is a closure. According to the characteristics of the closure, the inner function has the right to access the variable object of the outer function. So when iememery() is executed:
js_obj is a reference to a DOM element. The DOM element remains in the web page for a long time and will not disappear. An attribute of this DOM element, oncontextmenu, is also an internal function reference (closure) , and this anonymous function has a hidden association (scope chain) with js_obj
So a circular reference is formed. That is:
js_obj.oncontextmenu indirectly refers to js_obj In other words, a circular reference of this object Attribute, and indirectly refers to itself.
As long as there are circular references, memory leaks will occur under IE. Open your Windows Task Manager and keep refreshing the HTML page containing this code in IE to see if the memory usage of the Iexploer process keeps rising and will not be automatically recycled (lowered);
Solution:
function iememery(){
var js_obj = document.createElement("div");
js_obj.oncontextmenu = function(){ return false;}; js_obj.oncontextmenu = null;//Add this sentence to break the reference}
When a direct circular reference between js objects and dom objects occurs in IE, and there is no subsequent reference to them,
If it is IE 6, the memory leaks until the IE process is closed
If it is IE 7, the memory leaks until Until leaving the current page
If it is IE 8, the GC collector reclaims their memory, regardless of whether it is currently in compatibility mode or not.
The GC collector in the previous IE js engine could only process js objects, not DOM objects.