3

Consider this JavaScript code...

(function() {

    window.myNameSpace_callback = function() {
        // Do whatever.
        delete window.myNameSpace_callback;
    };

    // Assume this does not return JSON, but has JavaScript code to be executed
    // and also calls a user defined callback.
    $.getScript('http://someapi.com/?callback=myNameSpace_callback');

})();

jsFiddle.

The fact I used the jQuery library above should be irrelevant to the question.

After the delete line, the global does not exist. I'm doing this to keep this global only alive for as long as it has to be.

However, is it bad practice to delete a property from the global object which happens to be the current running function?

alex
  • 479,566
  • 201
  • 878
  • 984
  • 1
    I don't see anything particularly wrong with it -- except for whatever arguments one might have against mutable global variables in general. By the time the function begins to run, the reference to it has already been retrieved from the global object, so the attribute there is not used anymore after that. – hmakholm left over Monica Sep 06 '11 at 00:47
  • 2
    I think it is -- because to me it indicates that the approach used is either "too tricky" or "isn't idiomatic". –  Sep 06 '11 at 01:00
  • Hm, what's the purpose of deleting it? – Šime Vidas Sep 06 '11 at 01:37
  • @Šime It's a *once use* function and in the global only because it has to be. – alex Sep 06 '11 at 01:44
  • @alex I see. So I guess the idea is to free up a bit of the browser's memory, right? – Šime Vidas Sep 06 '11 at 01:53
  • @Šime More importantly to keep the global *clean*. – alex Sep 06 '11 at 02:00
  • @alex Hm, but is there a difference in that respect? I mean practically... If another script comes along which decides to use that global name, it's going do overwrite that name (nothing will break), just as if that name was never occupied. (And since you don't need that function anymore, the overwrite won't break any of your stuff neither.) – Šime Vidas Sep 06 '11 at 02:07

1 Answers1

4

There is nothing wrong with doing that.

The delete keyword removes references, not the actual function itself. You can't exactly destroy an object in Javascript; you can only remove all references to it. Garbage collection does the rest.

So calling delete on the reference to the function it is within won't matter as you're only removing the reference to it off the window namespace. The function will still exist as long as you still reference it.

window.myNameSpace_callback = function() {
    delete window.myNameSpace_callback;

    // We deleted the reference to the function off the window namespace,
    // but we can still access it using arguments.callee
    window.myNameSpace_callback_two = arguments.callee;
}; 

myNameSpace_callback();

myNameSpace_callback(); // Error, but what about...

myNameSpace_callback_two();
Community
  • 1
  • 1
Ben
  • 5,117
  • 2
  • 27
  • 26