JavaScript: resetting and emptying objects

JavaScript lacks of a method for emptying and resetting objects, thus freeing memory resources. For that reason, in this post I'm going to show you how to attach a method to every object to accomplish this task. This method loops through all the members of an objects and sets them to null:

if(typeof Object.prototype.empty !== 'function') {

 Object.prototype.empty = function() {
 
 
   for(var i in this) {
   
   
      this[i] = null;
   
   }
 
 
 };
  
      
  
}

A simple test:

function Class() {

  this.a = 'Test';

}

var myClass = new Class();
alert(myClass.a); // 'Test'

myClass.empty();
alert(myClass.a); // null

Leave a Reply

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