In C++ I can define a constructor and destructor explicitly, and then cout << “C or D Called” from with in the constructor/destructor function, to know exactly where.
However in JavaScript how do I know when an object is destructed. The example below is the case that concerns me.
I’m calling an internal function on a timeout and I’m wondering if the object stays alive as long as the timer is running, waiting to call next again.
User Click calls Control
// Calls Control
Control calls Message
var message_object = new Message( response_element );
Message calls Effects
new Effects().fade( this.element, 'down', 4000 );
message_object.display( 'empty' );
Effects
/**
*Effects - build out as needed
* element - holds the element to fade
* direction - determines which way to fade the element
* max_time - length of the fade
*/
var Effects = function( )
{
this.fade = function( element, direction, max_time )
{
element.elapsed = 0;
clearTimeout( element.timeout_id );
function next()
{
element.elapsed += 10;
if ( direction === 'up' )
{
element.style.opacity = element.elapsed / max_time;
}
else if ( direction === 'down' )
{
element.style.opacity = ( max_time - element.elapsed ) / max_time;
}
if ( element.elapsed <= max_time )
{
element.timeout_id = setTimeout( next, 10 );
}
}
next();
}
};
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
deletekeyword 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.