So I found this piece of code and it obviously works (as it has been in production for years):
window[someMethod] = function (tmp) {
callback({prop:"val"}, tmp);
// Garbage collect
window[someMethod] = undefined;
try {
delete window[someMethod];
}
catch (e) { }
if (head) {
head.removeChild(script);
}
// head refers to DOM head elem and script refers to some script file elem
};
Curious to know, how does it work?
- How can it set itself to
undefined
within its body andtry
todelete
itself? - Does the browser know to not execute the
undefined
anddelete
until the call is finished? And how? - If the browser deletes it right away, then what happens after? Does the last line run?
- Finally, do you guys see this leaking memory? If yes, how?
Hopefully this is making sense.
Remember you can't ever explicitly delete something in Javascript. All you can do is remove all the references to it and so let the garbage collector remove it on the next cycle. By the end of this function, the function itself is still in memory, but there are no external references to it. Next time the GC runs, it will spot this and deallocate its memory.
window[someMethod] is simply a reference. Only the reference is deleted, not the function itself. Once the function is done, and all reference to it are removed, garbage collection should take care of it, avoiding memory leaks.