JavaScript Objects: Destroying Them

I need to maintain a JavaScript object with some 30-40 properties that I update every few seconds. I read that in JavaScript there is no such thing as "freeing" memory, and the browser automatically garbage collects unused memory.

My question is: is it enough to set the object itself to null or do I need to set all its properties to null and then set it to null?

var obj = [];
obj[prop1] = "123";
obj[prop2] = "456"; 
//...and so on...

// now to release the obj, is it enough if I just did:
obj = null; 
+5
source share
4 answers

, . , , null ( ) ( ) , .

null : "", .

+1

, . , "" , -.

,

var a = {"testkey": "testval"};

var b = jQuery.ajax({
   url:"http://somewhere",
   method: "GET",
   onSuccess: function() {
      //this function is called asynchronously, moments later,
      //but as "a" is defined in the enclosing variable scope,
      //you can access it from here
      alert(a.testkey);
   }
});

null , .

+2

( ), null, - , DOM.

, node , onclick, , onclick null ( ).

<div id="delete_me">
  <span></span>
  <span></span>
</div>

var theDiv = document.getElementById('delete_me');
for (var i=0; i < theDiv.childNodes.length; i++) {
  theDiv.childNodes[i].onclick = function () {
    // stuff
  };
}

// Later...
// Delete stuff.
var divToDelete = document.getElementById('delete_me');

// Remove all the onclicks
for (var i=0; i < theDiv.childNodes.length; i++) {
  theDiv.childNodes[i].onclick = null;
}

// Delete the div
divToDelete.parentNode.removeChild(divToDelete);
+1

null . , , . delete :

delete obj;
0

All Articles