Jump to content

How to destroy things correctly?


clark
 Share

Recommended Posts

In actionscript you would get an error if you tried to call a method of an object which did not exist and I am guessing JS is the same.
 

function destroy(): void{     this._apple.destroy()   //error, you cannot call destroy() because this._apple is null or undefined}

So what I end up doing was this which worked for a decade:
 

function destroy(): void{     if (this._apple != null)     {          this._apple.removeEventsBlah...          this._apple.destroy();          this._apple = null;     }     }

But this feels primitive. When you have like 12 class members, and you got to check if they are null.

Apart from that, I read this is not accurate for JS? I should use typeof?

So if typeof variable === "undefined" 

Basically, how do you correctly destroy objects? Is it merely enough in JS just to null it....  this._apple = null.  I am not sure how stuff works without a virtual machine doing garbage collection where it is important to remove all listeners/references while I am struggling to figure out what is null in relation to undefined. 

Link to comment
Share on other sites

Yes it is enough just to set it to null if you want it empty. Do not set it to undefined.

 

Undefined is, of what I've known:

1. What is thrown when your variable is not initialized (var a;)

2. Calling an out of bounds array elements (a[5] when array length is actually 4)

3. Getting a value where a function doesn't return a value.

4. Passing parameter when it is not passed any value (function myMethod(a, b ) {} --> usage: myMethod(5), then b is undefined).

 

It is preferable, even if possible, not to use any uninitialized variables for any use (including typeof), in this case "undefined", until you assign it with value, which is at least a null value.

 

Regarding to your garbage collection issue, when the object is no longer used/have no reference whatsoever, it will be taken care by JavaScript, even if you don't set it to null. For example, you have a Human object that has a Hand object. When you set a human object variable to null, then Hand object will be garbage collected without you needing to destroy it in Human's destructor like C++, nor you need to manually call "human.cleanUp()" to set that hand object to null.

This is just the same as ActionScript, C#, and Java.

 

The only way to manage this automatic garbage collection is how you manage your variables around the application without losing them, like using object pooling.

Link to comment
Share on other sites

 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...