I want to have a bunch of objects, let’s say:
function Block() {
this.canvas;
}
blocks = [];
And I will at occasions specify:
block[x] = new Block();
and then:
block.canvas = document.createElement('canvas');
But I will also want to delete this new canvas to free up memory sometimes. Do I just need to do:
block.canvas = null; (or whatever the appropriate method is)
And then javascript will free up the memory at some stage? Or is there an explicit way to delete the object and free up the memory?
Thanks!
Memory, that is taken by objects, that are referenced nowhere, is recovered in JavaScript by the garbage collection (MDN docu on this).
So in order to free up the memory, you just have to delete all references to your
canvasobjects and in the next run of the garbage collector, the memory will be freed again.This can be done, like you did, using
block.canvas = null;or (depending on the objects/properties scope) bydelete block.canvas.But be sure, that you remove every reference. This can also be references by the DOM or any other object!