tags:

views:

33

answers:

3

Does the following function has memory leak?

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

    // blah...

};
A: 

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

Darin Dimitrov
+1  A: 

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;

KMan
Unless they have a next use...
Dan Beam
+1  A: 

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.

Dan Beam