Over a million developers have joined DZone.

Leak Free Javascript Closures

DZone's Guide to

Leak Free Javascript Closures

· ·
Free Resource
Javascript closures can be a powerful programming technique. Unfortunately in Internet Explorer they are a common source of memory leaks. Therefore I propose a method to create closures that don't leak memory.


Function.prototype.closure = function(obj)
  // Init object storage.
  if (!window.__objs)
    window.__objs = [];
    window.__funs = [];

  // For symmetry and clarity.
  var fun = this;

  // Make sure the object has an id and is stored in the object store.
  var objId = obj.__objId;
  if (!objId)
    __objs[objId = obj.__objId = __objs.length] = obj;

  // Make sure the function has an id and is stored in the function store.
  var funId = fun.__funId;
  if (!funId)
    __funs[funId = fun.__funId = __funs.length] = fun;

  // Init closure storage.
  if (!obj.__closures)
    obj.__closures = [];

  // See if we previously created a closure for this object/function pair.
  var closure = obj.__closures[funId];
  if (closure)
    return closure;

  // Clear references to keep them out of the closure scope.
  obj = null;
  fun = null;

  // Create the closure, store in cache and return result.
  return __objs[objId].__closures[funId] = function ()
    return __funs[funId].apply(__objs[objId], arguments);

Usage example:

function attach()
  var element = document.getElementById("my-element");
  element.attachEvent("onclick", function()
      alert("Clicked: " + this.innerHTML);

So now we have truly leak free closures.

In addition we can also easily remove an object from the global array. The following code allows the garbage collector to free an object if there are no other references to it: 

window.__objs[obj.__objId] = null;

Source: Leak Free Javascript Closures

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}