Self destructing Javascript function - How does it work?

Viewed 4002

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?

  1. How can it set itself to undefined within its body and try to delete itself?
  2. Does the browser know to not execute the undefined and delete until the call is finished? And how?
  3. If the browser deletes it right away, then what happens after? Does the last line run?
  4. Finally, do you guys see this leaking memory? If yes, how?
3 Answers
Related