Closures will be a memory leak it?

Found a bunch of online tutorials say closures Closures cause memory leaks, specifically to check the next book, which has been found to be a misunderstanding.

js original elevation had this to say : As the previous version of IE9 uses different garbage collection JScript objects and COM objects. Therefore closures in these versions of IE will cause special problems. Specifically, if the closure of the scope chain holds an HTML element, then it means that the element will not be destroyed.

Closure means that memory leaks caused by an older version of IE bug, closures in the real situation will not cause a memory leak.

Here's how to fix the old version of IE memory leaks:

function assignHandler(){
    var element = document.getElementById("someElement");
    element.onclick = function(){
        alert(element.id);
    };
}

The above code creates a closure element as an element of an event handler, and this closure in turn creates a circular reference. Since the anonymous function saves a reference to assignHandler () event objects, so it will not lead to reduction in the number of references element. As long as anonymous function exists, element reference number is at least 1, so the memory it will never be recovered, this is IE problem, so closures and memory leaks have not half dime.

Preface solutions already mentioned, put a copy of element.id is stored in a variable, eliminating the variable loop closure referenced while the element variable to null.

function assignHandler(){
    var element = document.getElementById("someElement");
    var id = element.id;
    element.onclick = function(){
        alert(id);
    };
    element = null;
}

Summary: Closure and will not cause a memory leak, but due to a previous version of IE9 uses different garbage collection JScript objects and COM objects, resulting in memory can not be recovered.

Precautions closures are used

1) Due to the closure will make the function of the variables are stored in memory, memory consumption is large, it can not be abused closure, otherwise it will cause performance problems webpage in IE may lead to memory leaks. The solution is, before exiting the function will delete all local variables are not used.

2) Closure will function outside the parent, the parent function changes the value of the internal variable. So, if you take the parent function as an object (object) to use, the closure of its public methods (Public Method) as, the internal variable as its private property (private value), then you must be careful not to just change the value of the parent function of internal variables.

Reference: Learning Javascript closure (Closure) - Ruan Yifeng

 

Guess you like

Origin www.cnblogs.com/jianxian/p/11973251.html