- Home /
Is there a way to make a class destructor in javascript?
I have classes that instantiate game objects. I want the game objects to get destroyed when the owner object is destroyed through normal means (garbage collection I suppose). This could easily be done by using a destructor, but is this possible in Javascript?
As a workaround, I manually call a cleanup method immediately before clearing the last reference to the object, but that's not as elegant.
Answer by Eric5h5 · Apr 11, 2011 at 07:08 PM
The C# destructor syntax doesn't work in JS. You can use Finalize(), but you get a warning about how overriding Finalize is bad practice and you should use the destructor syntax (yet there's no hint as to what the destructor syntax might be, if in fact it exists).
However, I think it's a moot point, because Destroy is from MonoBehaviour, and calling MonoBehaviour.Destroy in Finalize (or in the destructor in C#) in a class that doesn't inherit from MonoBehaviour results in a cryptic run-time error message anyway. So as far as I know, the whole idea isn't possible.
Answer by DaveA · Apr 11, 2011 at 06:35 PM
You might find these of use:
http://msdn.microsoft.com/en-us/library/2z08e49e(v=vs.90).aspx#Y300
http://msdn.microsoft.com/en-us/library/hks5e2k6(v=vs.90).aspx