0

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?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
ojhawkins
  • 3,200
  • 15
  • 50
  • 67
  • As I can see, there are no actions processed regarding foo variable... Maybe this code is just wrong? – monkeyinsight Apr 30 '14 at 03:47
  • My understanding is the `foo` variable is created so the global object is not being referenced for the duration of the statments execution. The actual funciton contains about 1000 lines of code @monkeyinsight – ojhawkins Apr 30 '14 at 03:50
  • Your comment "My assumption is foo will be dereferenced once statement has finished executing therefore would be no need to explicitly do it." You mean the execution of that variable after the whole script is executed? U would need the delete foo to remove all the reference made to foo and also to make it undefined. – SSS Apr 30 '14 at 04:06
  • Refer to this link possible duplicate [http://stackoverflow.com/questions/742623/deleting-objects-in-javascript][1] [1]: http://stackoverflow.com/questions/742623/deleting-objects-in-javascript – Gian Carlo Apr 30 '14 at 04:08

1 Answers1

2

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;
jfriend00
  • 683,504
  • 96
  • 985
  • 979