JavaScript uses garbage collection to automatically delete objects when they are no longer referenced. There is no concept of destructors or finalizers.
You can't observe when an object is deleted by the garbage collector, nor is it predictable.
As of ES2021, finalizers were added to the specification.
To use that feature, you create a FinalizationRegistry, which notifies you when any of the associated objects get garbage collected.
You can use it like that:
const reg = new FinalizationRegistry((id: number) => {
console.log(`Test #${id} has been garbage collected`);
});
class Test{
id: number;
constructor(id: number){
this.id = id;
reg.register(this, this.id);
// ^^^^^^^--- This is the "testament", whatever value, which will be passed to the finalization callback
}
}
{
const test1 = new Test(1);
const test2 = new Test(2);
}
Note that when the callback is called, the object had already been garbage collected; only its "testament" (or as MDN puts it, less dramatically, the "held value") is given to the finalizer.
If you need access to some properties of the object in the finalizer, you can store them inside the testament, which, in this case, can (although not necessarily will) be garbage collected just after the original object:
Note that the specification doesn't guarantee when garbage collection happens, so the finalizer may not even be called if the object stays in the memory.