kakashi_69_xd
kakashi_69_xd8mo ago

Finalization not working

I can't get the gc to run a destructor.. At first I thought that I'm making some kind of mistake here but I don't know where.. I was trying to make a Drop trait
abstract class Drop {
#registry=new FinalizationRegistry((_)=> this.drop());
constructor() {
this.#registery.register(this, "");
}
protected abstract drop(): void;
}

class Foo extends Drop {
protected drop(): void {
console.log("Foo was dropped");
}
}

const _foo=new Foo();
abstract class Drop {
#registry=new FinalizationRegistry((_)=> this.drop());
constructor() {
this.#registery.register(this, "");
}
protected abstract drop(): void;
}

class Foo extends Drop {
protected drop(): void {
console.log("Foo was dropped");
}
}

const _foo=new Foo();
Then I tried to copy some code that seemed to work from a conf and also mdn but the destructor was never called..
const obj={ xd: "xd" };

const registry=new FinalizationRegistry (heldValue=> console.log(`${heldValue} was dropped`));

registery.register(obj,obj.xd);
const obj={ xd: "xd" };

const registry=new FinalizationRegistry (heldValue=> console.log(`${heldValue} was dropped`));

registery.register(obj,obj.xd);
2 Replies
Andreu Botella (they/them)
FinalizationRegistry only calls the callback after the object is GC'd which means at that point there can't be any remaining references to the GC'd object I think () => this.drop() is actually keeping a reference to this alive which means there is no point at which there are no remaining references in JS there's no way to have a destructor that accesses the object the closest you can have is the using proposal (currently stage 3)
kakashi_69_xd
kakashi_69_xdOP8mo ago
I can't trust the user yk.. It's not guaranteed that he/she will declare the object using using