Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Leak Free Javascript Closures (See related posts)

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.

Solution:

   1  
   2  Function.prototype.closure = function(obj)
   3  {
   4    // Init object storage.
   5    if (!window.__objs)
   6    {
   7      window.__objs = [];
   8      window.__funs = [];
   9    }
  10  
  11    // For symmetry and clarity.
  12    var fun = this;
  13  
  14    // Make sure the object has an id and is stored in the object store.
  15    var objId = obj.__objId;
  16    if (!objId)
  17      __objs[objId = obj.__objId = __objs.length] = obj;
  18  
  19    // Make sure the function has an id and is stored in the function store.
  20    var funId = fun.__funId;
  21    if (!funId)
  22      __funs[funId = fun.__funId = __funs.length] = fun;
  23  
  24    // Init closure storage.
  25    if (!obj.__closures)
  26      obj.__closures = [];
  27  
  28    // See if we previously created a closure for this object/function pair.
  29    var closure = obj.__closures[funId];
  30    if (closure)
  31      return closure;
  32  
  33    // Clear references to keep them out of the closure scope.
  34    obj = null;
  35    fun = null;
  36  
  37    // Create the closure, store in cache and return result.
  38    return __objs[objId].__closures[funId] = function ()
  39    {
  40      return __funs[funId].apply(__objs[objId], arguments);
  41    };
  42  };


Usage example:

   1  
   2  function attach()
   3  {
   4    var element = document.getElementById("my-element");
   5    element.attachEvent("onclick", function()
   6      {
   7        alert("Clicked: " + this.innerHTML);
   8      }.closure(element));
   9  }


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:

   1  window.__objs[obj.__objId] = null;


Source: Leak Free Javascript Closures

You need to create an account or log in to post comments to this site.


Click here to browse all 5307 code snippets

Related Posts