Why object has to be nulled for IE after it was document.getElementById-ed?

↘锁芯ラ 提交于 2020-01-01 11:45:11

问题


I often see in third party JavaScript code that after:

var el = document.getElementById(elementId);

object is often nulled and comment along this operation says that it is done for IE:

el = null; // IE

What's the real purpose? Any resource on that?


回答1:


By nixing a reference they break the corresponding cyclic dependency between the DOM object and JavaScript objects, which are controlled by different sub-systems in older IE (thus being impossible to be garbage-collected).

For example:

var el = document.getElementById(elementId);
el.onclick = function () { // here the cyclic reference is created
    /...
};

The JavaScript subsystem has now a reference to the el element, and the DOM subsystem (the el element) has a reference to the JavaScript object (the function plus what it closes in).

You don't have to worry, though, if you add the listeners via addEventListener.

To read more about common memory leak pitfalls, see http://www.ibm.com/developerworks/web/library/wa-memleak/.



来源:https://stackoverflow.com/questions/6646419/why-object-has-to-be-nulled-for-ie-after-it-was-document-getelementbyid-ed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!