Do you know what may cause memory leaks in JavaScript?

前端 未结 5 836
星月不相逢
星月不相逢 2020-11-30 22:41

Do you know what may cause memory leaks in JavaScript? I am interested in browsers: IE 7, FireFox 3, Safari 3

5条回答
  •  甜味超标
    2020-11-30 23:07

    Here is a classic memory leak in IE:-

    function body_onload()
    {
        var elem = document.getElementById('someElementId');
        // do stuff with elem
        elem.onclick = function() {
            //Some code that doesn't need the elem variable
        }
     }
    

    After this code has run there is circular reference because an element has a function assigned its onclick event which references a scope object which in turn holds a reference to element.

    someElement->onclick->function-scope->elem->someElement

    In IE DOM elements are COM based reference counting objects that the Javascript GC can't cleanup.

    The addition of a final line in the above code would clean it up:-

    var elem = null;
    

提交回复
热议问题