Javascript closure : Memory Leak
While you are adding 'listeners' make sure you are removing it, if you are using the query for long time.
this.listeners = new Object();
or
this.listeners[e] = new Object();
this will add object to listener as array, but not removing them at any point.
This may be the reason for Memory Consumption. It may not leak, its assignment of objects. that consumes your RAM using browser. :)
You create closures that hold a reference to an EventHandler
instance via the handler
variable. One of the closures remains after the image has been loaded:
handler.addListener("ImageLoaded", handler, function() { Loader.files[src] = function(fnct) { fnct(img); } });
It's the inner function function(fnct) {...
. The instance of EventHandler
cannot be freed as long as the closure exists. Your only solution is to get rid of that closure. Or you free the instance manually, if possible. The following might work for you:
handler.fire("Delete");handler = undefined;
Chrome's memory profiler shows you the object's retaining tree, which is just another way to say "Who is holding a reference that object". In your example it's EventHandler <- handler (the variable of the LoadImage method as incorporated by the closure) <- house.jpg, which actually is Loader.files[src]
and has the value function(fnct) { fnct(img); }
.
I don't know why it is not garbage collected, but adding the destroy method to the instance instead of the prototype and setting self
to null, will apparently work:
var MyClass = function() { this.x = 1; var self = this; this.do_thing = function() { self.x++; }; this.destroy = function() { delete this.do_thing; self = null; };};var me = new MyClass();me.do_thing();me.destroy();me = null;