Class destructors

Calls when a class or object is about to be garbage collected or manually destroyed, like destructors in C++. For there's garbage collection in JavaScript, users should be able to control whether the class should be destroyed when exiting the scope or not.

This could greatly reduce the chance of memory leaking in JavaScript. Adds with defer, we could achieve a very primitive memory management method in JavaScript.

JavaScript now has FinalizationRegistry for trying to run code when a reference is dropped.

Though there are no guarantees that the callback will be called as that detail depends on the implementation of the garbage collector the JS engine uses. I also believe that there are security restrictions around exposing GC timing. Maybe someone else will be able to link to something about those.

The EcmaScript spec does not specify that JS should have a garbage collector, it is an implementation detail. The only mention it seems to make is this:

the object otherwise became inaccessible and subject to resource reclamation by the implementation's garbage collection mechanisms

ECMAScript® 2020 Language Specification