开发者

Memory leak in JavaScript for event handing

开发者 https://www.devze.com 2023-01-17 10:11 出处:网络
Does the following function has memory leak? var d = document.getElementById(\"d\"); d.onclick开发者_C百科 = function() {

Does the following function has memory leak?

var d = document.getElementById("d");
d.onclick开发者_C百科 = function() {

    // blah...

};


<div id="parent">
<span id="child">I am a span</span>
</div>

this is okie

    var d = document.getElementById("child");
    d.onclick = function() {

    // blah...    
};

//clearing an event from dom before removing handler from it will result in memory loss

now doing this will start leaking memory

   document.getElementById("parent").innerHTML="";


No, there's no memory leak here.

Additionally, you can use array de-referencing if you want to just do it in one line -

document.getElementById("d").onclick = function() {
    // blah...
};

but this is dangerous if the element isn't present (or the DOM's not ready, etc.), as document.getElementById returns null if the object isn't found in the DOM (and though null is an object when you typeof, it's not cool with you trying to set properties on it).

Ah, the quirks of JavaScript.


This is not memory leak. It's attaching onclick handler to a DOM element and is quite common.


No.

All local variables, that is variables declared inside a function(on stack) tends to lose the scope as soon as the method call is complete.

Also, when you are done with the d you can delete it as well; delete d;

0

精彩评论

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