开发者

Is `delete`ing a reference to a global function within itself a bad practice?

开发者 https://www.devze.com 2023-04-02 09:19 出处:网络
Consider this JavaScript code... (function() { window.myNameSpace_callback = function() { // Do whatever.

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?


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();
0

精彩评论

暂无评论...
验证码 换一张
取 消