I have a case where I have a variable in my JavaScript that will be used to store the reference to several instances of a class. The class creates a div based window, kind of like a lightbox, and then when I call the class’ removeWindow method, the div window elements are removed from the DOM. So a sequence might be like this:
var divWindow = null;
divWindow = new DivWindowClass(...);
/* do some stuff with the window */
divWindow.removeWindow();
Later on in the code I create a window again with different content, but I also want to be able to check if the divWindow variable is referencing anything.
Is it correct to just do:
divWindow.removeWindow();
divWindow = null;
if (divWindow == null) { /* etc. */ }
/* later in the code */
divWindow = new DivWindowClass(...); /* with different content than first one */
or does that cause memory issues with the JavaScript garbage collection? If I set divWindow to null, will that signal to the garbage collection to gather up my object and get rid of it, or is there something else I need to do to be tidy?
As always, thanks in advance!
Well it depends. If you have a function defined or expressed below the divWindow for example, that would mean divWindow is considered reachable by the garbage collector, at least for as long as that function exists. In that case, setting divWindow to null would actually cause the GC to clean it up on its next cycle. However, if that’s not the case, “nulling” a variable won’t help it anymore than normal. If you posted the entirety of your code, I could probably tell you more.
There is no explicit way to free up memory in javascript. The best you can do is to be aware of all references to your object, be aware of how reachable it is, and make sure the object is unreachable when you don’t need it anymore. After you do that, ultimately, you have to learn to trust the garbage collector, which isn’t so easy when you’re coding something that you want to run in IE for example.
(ps: I also want to knock out a comment made above. The
deleteoperator is for removing properties from an object. It doesn’t “delete” variables, and it doesn’t free up memory. In fact, javascript will throw if you dodelete foo;in strict mode.)