Gáb*_*pák 48 javascript destructor typescript
TypeScript中有析构函数吗?如果没有,我该如何删除对象?我尝试过destructor(),~ClassName()但它没有用.
Rya*_*ugh 51
JavaScript使用垃圾收集在不再引用对象时自动删除对象.没有析构函数或终结符的概念.
您无法观察垃圾收集器何时删除对象,也无法预测.
FZs*_*FZs 15
从 ES2021 开始,终结器已添加到规范中。
要使用该功能,您需要创建一个FinalizationRegistry,它会在任何关联对象被垃圾收集时通知您。
你可以这样使用它:
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);
}
Run Code Online (Sandbox Code Playgroud)
请注意,当回调被调用时,该对象已经被垃圾回收了;只有它的“遗嘱”(或者正如 MDN 所说,不太戏剧化的是“持有值”)被赋予终结器。
如果您需要访问终结器中对象的某些属性,则可以将它们存储在遗嘱中,在这种情况下,可以(尽管不一定会)在原始对象之后被垃圾收集:
interface TestTestament{
id: number,
intervalid: ReturnType<typeof setInterval>
}
const reg = new FinalizationRegistry((testament: TestTestament) => {
console.log(`Test #${testament.id} has been garbage collected`);
clearInterval(testament.intervalid);
});
class Test{
private testament: TestTestament;
constructor(id: number){
this.testament = {
id,
intervalid: setInterval(() => {
console.log(`Test interval #${id}`);
}, 1000)
};
reg.register(this, this.testament);
}
}
{
const test1 = new Test(1);
const test2 = new Test(2);
}
Run Code Online (Sandbox Code Playgroud)
请注意,规范不保证垃圾收集何时发生,因此如果对象保留在内存中,则终结器甚至可能不会被调用。
| 归档时间: |
|
| 查看次数: |
29970 次 |
| 最近记录: |