Can someone explain this javascript memory leak sc

2019-04-13 11:41发布

问题:

http://www.ibm.com/developerworks/web/library/wa-memleak/ On this link, Listing 5 describes a situation where obj is a reference to a dom element, and the dom element has a reference to obj, and therefore causes a memory leak. I'm struggling to see what in the code makes the DOM element have a reference to obj. Could someone explain it to me?

Taken from the page:

In Listing 5 you see a closure in which a JavaScript object (obj) contains a reference to a DOM object (referenced by the id "element"). The DOM element, in turn, has a reference to the JavaScript obj. The resulting circular reference between the JavaScript object and the DOM object causes a memory leak.

Listing 5. Event handling memory leak pattern

<html>
<body>
<script type="text/javascript">
document.write("Program to illustrate memory leak via closure");
window.onload=function outerFunction(){
    var obj = document.getElementById("element");
    obj.onclick=function innerFunction(){
    alert("Hi! I will leak");
    };
    obj.bigString=new Array(1000).join(new Array(2000).join("XXXXX"));
    // This is used to make the leak significant
};
</script>
<button id="element">Click Me</button>
</body>
</html>

回答1:

the memory leak exists because of the circular reference between obj and onclick.

Normally, after the execution of onload, all variables in its scope will be garbage collected and erased. In javascript however, a function-scope is not always deleted after the execution. This is called closures.

For example, if an outer object references something in this scope. In this case onclick references outerFunction and outerFunction is referenced by obj

If obj would be set to null, there would not be a reference to something within the onload-scope.

One can argue that the reference ist still to outerFunction, which is correct. But outerFunction is not bound anymore to the onload-scope, making this scope valid to be cleaned by the garbage collector.