3

I understand the concept of circular references in JavaScript and the importance of avoiding them to prevent memory leaks, but I have not been able to find any information about how assigning functions that are members of closures or prototypes to event handlers impacts garbage collection.

For example let's say I wrote either one of the following:

var o = {};
o.var = 10000000;
o.func = function() { /*Do something that does not involve o.var*/ };

function p() { }
p.prototype.var = 100000;
p.prototype.func = function () { /*Do something that does not involve p.var*/ };

... and then proceeded to do either one of these:

var div = document.getElementByID('div');
div.onclick = o.func;

var instance_of_p = new p();
var div = document.getElementByID('div');
div.onclick = instance_of_p.func;

Would the assignment of func() to a DOM event handler prevent the entire object from ever be collected by the GC?

Alexis Wilke
  • 19,179
  • 10
  • 84
  • 156
MadRabbit
  • 31
  • 1
  • 3
  • That might depends on the engine. Since `func` closes over `o`, it does have access to it. Some engines might recognize that it does not access `o` though. – Felix Kling May 24 '12 at 19:12
  • As far as I know it used to happen in earlier versions of IE... And you have to refer to a html element, which refers to a JS object, which refers to the same html element (?)... i'M not sure about the last one... =) – benqus May 24 '12 at 19:19
  • Actually, I did that on purpose. While it may seem silly in such a short example, in long stretches of code where I am referencing the same element multiple times, I will assign it to a variable for the sake of legibility and efficiency. This strategy is based on the GC collecting the variable when I am finished, because it is only being used to do assignment to the DOM and not being referenced by any other objects. If that is an incorrect statement, I would love to know... – MadRabbit May 24 '12 at 21:24

1 Answers1

0

Yes. Read this excellent answer on how gc works in JavaScript. In your case, o is still available in the global or closure scope, so it won't be collected. It is still available to the function, altough might not be used.

BTW: There is no problem with circular references.

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375