Javascript delete statement

元气小坏坏 提交于 2019-12-12 04:54:01

问题


Q: I am trying to work out why there is a delete statement in this code?

My assumption is foo will be dereferenced once statement has finished executing therefore would be no need to explicitly do it.

(function () {
    var foo = globalObject;

    foo.bar = function () {
        //code here
    }
    delete foo;
}());

What is going on here?


回答1:


See this article on when To and Not To use the delete operator.

This does not appear to be a proper use.

Local variables cannot be deleted as they are marked internally with the DontDelete attribute. There are occasions when you might want to clear a local variable (if you want to release any memory used by it and the scope may survive indefinitely in a closure), but you don't use the delete operator for this purpose - you can just set it to null.

In normal functions that don't create closures, any local variables will simply be garbage collected when the function completes and if there are no other references to their data in other code, that data will be freed by the garbage collector.

The only time you need to worry about clearing references to data is when you have a scope that will exist for a long duration of time (closure or global) and you no longer need that data and it's useful to free up its memory usage.

FYI, the most common use of the delete operator is to remove a property from an object as in:

var foo = {x: 1, y: 2};
delete foo.x;


来源:https://stackoverflow.com/questions/23379315/javascript-delete-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!