开发者

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

开发者 https://www.devze.com 2023-03-19 20:02 出处:网络
I often see in third party JavaScript code that after: var el = document.getElementById(elementId); object is often nulled a开发者_开发百科nd comment along this operation says that it is done for I

I often see in third party JavaScript code that after:

var el = document.getElementById(elementId);

object is often nulled a开发者_开发百科nd comment along this operation says that it is done for IE:

el = null; // IE

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


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/.

0

精彩评论

暂无评论...
验证码 换一张
取 消