Reputation: 10161
Do I have to destroy instances myself? ...if I don't assign them a variable...will they automatically go away?
new ImageUploadView();
vs
var Iu = ImageUploadView();
Upvotes: 2
Views: 562
Reputation: 739
With large objects, it's not necessarily a good practice to assume that the browsers built in garbage collector will clean up once it's out of scope. You're better off to clear it ourself using "delete". For example:
delete MyImageUploadView;
Edit: it may be preferable to set the object to null if it isnt being referenced as a property.
Upvotes: 0
Reputation: 707148
If there is no reference to an object in javascript, the garbage collector will clean it up.
The way the garbage collector works is it looks for javascript objects for which nobody has a reference to. If nobody has a reference to it, then it can't be used again, so it can be deleted and the memory it occupied reclaimed. On the other hand, if any javascript entity still has a reference to the object, then it is still "in use" and cannot be deleted.
In your first code example:
new ImageUploadView();
unless the constructor of the object stores away the this
pointer into some other variable or object or creates some closure that causes references to the object to be held, then there will be no reference to this new object and it will be cleaned up by the garbage collector.
If you second code example:
var Iu = ImageUploadView();
as long as the Iu
variable exists and stays in scope it will contain whatever the ImageUploadView()
function returns. Note, the second example, is just executing a function and storing it's value. It is not necessarily creating anything. If ImageUploadView()
just returns true
, then that's all the Iu
variable will contain.
Upvotes: 3
Reputation: 91467
The first method is fine. Assuming that the instance of ImageUploadView
is appropriately cleaning up after itself, it will be collected by the garbage collector.
Upvotes: 0