Memory leak in JavaScript for event handing
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;
精彩评论