JavaScript: object destructors

Many web programming languages have the notion of destructors, that is, magic methods that free the memory occupied by an object when this is no longer needed. JavaScript has no notion of destructors because of its peculiar way of handling memory. However, although this might seem a little bit weird, sometimes there are situations where we actually need to destroy objects. A typical case scenario is Ajax, for example when we need to free memory from an unsuccessful XMLHTTPRequest transaction.

So far I've tried different approaches, and I find out that perhaps the best way to accomplish this task is to set an object or its instances to null or use delete(), though the former should be carefully handled because this kind of value can actually rise a JavaScript error. Here's an example:

function A(value1, value2) {

    this.prop1 = value1;
    this.prop2 = value2;


var a = new A('foo', 'bar');

The object in question now contains two properties with two different values. I've tested several combinations and these are the results:

  1. a = null; will raise an error, but it actually destroys the object's instance
  2. a = function(){}; will set the properties to undefined, because an object is still a function
  3. even the following approaches will set the properties to undefined:
    • a = new function(){};
    • a = {};
    •     var b = function(){};
          a = new b();

Given the preminence of the concept of functions in JavaScript (where, as you know, they work as objects and constructors as well) and the inner, prototypical nature of its way of handling objects and inheritance, it's extremely difficult to address the topic of destructors from within a function / object. I think that this was only a matter of curiosity from my part, nothing more.

Leave a Reply

Note: Only a member of this blog may post a comment.