Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

closures - Javascript delete statement

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...