Function.prototype.closure = function(obj)
// Init object storage.
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;
__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;
__funs[funId = fun.__funId = __funs.length] = fun;
// Init closure storage.
obj.__closures = ;
// See if we previously created a closure for this object/function pair.
var closure = obj.__closures[funId];
// 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);
var element = document.getElementById("my-element");
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;