views:

435

answers:

10

Coming from C++ it is hard grained into my mind that everytime I call new I call delete. In JavaScript I find myself calling new occasionally in my code but (hoping) the garbage collection functionality in the browser will take care of the mess for me.

I don't like this - is there a delete method in JavaScript and is how I use it different from in C++?

Thanks.

+8  A: 
var component = new Component();
component = null; // delete this at next garbage collection
MBO
+1 for a legitimate way to delete.
N 1.1
To people not accustomed to GC, this conveys the **opposite** meaning to `delete`. To them, it appears that the intention is to leave the memory allocated forever, so I would imagine it doesn't provide the "comfort" the asker seems to be looking for. Then again, if he's just looking for a way to communicate the intent that the object is no longer needed (for readability), this succeeds.
gWiz
+4  A: 

Here is a related question which talks about the Javascript CG.

http://stackoverflow.com/questions/864516/what-is-javascript-garbage-collection

Kevin
A: 

There is a delete in Javascript, but trust me: it's way different than delete in something like C++. I recommend you don't even think about using it until you're more comfortable with Javascript.

Garbage collection works, though it doesn't defeat the problem of memory leaks.

Pointy
+1  A: 

There is a delete. However, an actual need for it will be rare. It's not like C++ delete, though.

delete in JavaScript will remove a property from an object. Subsequent accesses of that property will return undefined. I assume it will be able to free any associated memory on subsequent garbage collects.

Jonathon
+2  A: 

Taken outside of the context (the browser) the javascript is fully capable of reclaiming the memory through garbage collection. Going back to reality garbage collection in combination with DOM model can cause memory leaks.

Here is one article http://www.ibm.com/developerworks/web/library/wa-memleak/ you can find more details about it

mfeingold
+1  A: 

Don't use delete in JavaScript unless you are removing event handlers. Even then, we only do this because there is a memory leak associated with this practice in older versions of IE. Douglas Crockford explains this pretty well. In his case, he doesn't even use delete. He simply sets the values in question to null.

EndangeredMassa
+8  A: 

Incidentally, the "new" keyword isn't really necessary in javascript, and has nothing (directly) to do with allocating memory. All "new" does is pass a new, empty object called "this" (this = {}) as a hidden argument to the function.

var MyClass = function(){
    // fresh empty object "this" gets passed to function
    // when you use the "new" keyword 
    this.method = function(){}
}

var myInstance = new MyClass();

Javascript can get kind of hairy with nested closures and multiple "this" variables floating around in different scopes. I prefer to do it this way:

var MyNoNewClass = function(){
    // I find this more explicit and less confusing
    var self = {}
    self.method = function(){}
}

var myNoNewInstance = MyNoNewClass()
morgancodes
And delete doesn't deallocate memory directly, it just assigns undefined to the given property of an object
Bob
false. delete != undefined
Alsciende
@Alsciende Yes, you're right, thanks. delete, however, still doesn't deallocate memory directly like it does in other languages, it only removes a property from an object
Bob
+4  A: 

All JavaScript memory is referenced, but not in the traditional sense. Memory is referenced not by memory address but by a string. In this code:

var x = new someObj();

That object is referenced by the string "x" from that point forward. x is not a pointer to some memory on the heap at that point. If you assigned x a property then:

x.someProp = 42;

Then someProp is a string in memory referencing the value 42. Consequently that lets you use array notation to access it by it's string representation:

x["someProp"]++;

It's also why variables can hold any value as they don't have need of size.

Memory is collected in JavaScript, effectively, when no more strings (aka variables or property names) are referencing it. That object will be collected when x is assigned any other value. You could set it to null, undefined, or anything else and that memory will be collected.

That is, it will be collected when the browser or whatever JavaScript engine gets around to it.

Delete only removes properties from objects. From then on attempting to access that property will return undefined. For the most part, the following 2 lines of code are equivalent:

x["someProp"] = undefined;
delete x.someProp;

Edit: Ok, internally the two lines aren't the same. The delete operator will remove the "someProp" reference from memory, while setting it to undefined won't. I think. I can't find anything in the specs about setting a variable or property to undefined, but I don't think doing so does anything special.

The important thing to note is that you won't be able to delete properties that have a certain flag set, but you can set them to null or undefined (if they're not wrapped by a setter and even allow that to happen).

Bob
The last bit about delete is wrong. Assigning undefined and using delete are two separate things.
Alsciende
@Alsciende strictly speaking perhaps, but for all intents and purposes they accomplish the same thing. Still, I can see what I wrote is wrong in the strict sense so I'll edit, thanks
Bob
+1  A: 

From the MDC:

The delete operator deletes a property of an object, or an element at a specified index in an array.

The delete operator in my opinion is only useful when you want to remove a property from an object. But since there might be other references to the property that it were referencing, it wont be really GCed. If you want something to be GCed, you need to remove all pointers pointing at it and also free the closures containing references to it (more info on the topic).

Pablo Cabrera
+1  A: 

new creates objects from a constructor. delete removes properties from an object. These are two very different things.

You don't have to delete objects you created. The GC takes care of this.

delete o.fu is different from o.fu = undefined. Try this:

var o = {};
alert(o.hasOwnProperty('fu')); // -> false
o.fu = undefined;
alert(o.hasOwnProperty('fu')); // -> true
delete o.fu;
alert(o.hasOwnProperty('fu')); // -> false
Alsciende