When are JavaScript objects destroyed?
There is no dynamic memory managment in ECMAscript at all. A Garbage Collector will take care of anything that required memory in your script. So actually the question should be more like,
"How does the Garbage Collector know when it can free memory for objects"
Simply spoken, most GC's look if there are any active references. That might be due to parent context object, prototype chains or any direct access to a given object. In your particular instance, anytime setTimeout
gets executed, it'll call next()
which closes over the .fade()
parent context and the .face()
function in turn holds a closure to the Effects
function( context ).
That means, as long as there are calls to setTimeout
, that whole construct is held in memory.
You can help old'ish GC implementations sometimes a little bit, by null
ing variables-/references to it is able to collect some stuff earlier or at all, but modern implementatios are pretty smart about this stuff. You actually don't have to care about things like "Object/Reference live times".
Edit 2020: This answer from @BuffyG is much more accurate and useful than my old answer below. Object destruction is about more than memory leaks, and modern JavaScript has none of the patterns I mentioned.
JS objects don't have destructors per se.
JavaScript objects (and primitives) are garbage collected when they become inaccessible, meaning when there is no possible reference to them in the current execution context. The JavaScript runtime has to continuously monitor for this. So unless you use the delete
keyword to remove something, then its destruction is sort of under the hood. Some browsers are bad at detecting references left in closure scope (I'm looking at you, Redmond) and that's why you often see objects being set to null at the end of functions--to make sure that memory is freed in IE.
This notion that object destruction is reducible to garbage collection for memory strikes me as dangerously misleading, as the problem isn't reducible to freeing memory.
Destructors are responsible for releasing other resources, such as file descriptors or event listeners, which aren't dealt with automagically by garbage collection. In such cases destructors are absolutely required to unwind state before memory is released, or you will leak resources.
In such cases it's a problem that destructors aren't a first-class notion, whether they need to be called explicitly or can be called implicitly after an object becomes unreachable.
The best way to deal with this is to document your modules appropriately if they need destructors to be used and to underline resource leak scenarios failing such use.