TypeScript 中有析构函数吗?如果没有,我该如何删除一个对象?
我尝试过
destructor()
和 ~ClassName()
,但都没有起作用。destructor()
和 ~ClassName()
,但都没有起作用。JavaScript使用垃圾回收机制,在对象不再被引用时自动删除它们。没有析构函数或终结器的概念。
你无法观察到垃圾回收器何时删除对象,也无法预测。
从ES2021开始,规范中添加了finalizers。
要使用该功能,您需要创建一个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);
}
请注意,当回调被调用时,对象已经被垃圾回收;只有它的“遗嘱”(或者按照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);
}
你实际上可以
class MyClass {
constructor(input1, input2){
this.in1 = input1;
this.in2 = input2;
}
}
let myObject = {};
try {
myObject = {
classHandler: new MyClass('1','2')
}
} catch (e) {
} finally {
delete myObject.classHandler
// garbageCollect
if (global.gc) {global.gc()}
}
delete
运算符只是删除了对该对象的引用,垃圾回收仍然像往常一样不可预测。 - John Montgomerydelete
经常存在很多困惑,特别是对于JavaScript的初学者,我担心这个答案会延续这种情况。**delete
与垃圾回收无关。**实践中,似乎实现可预测的资源清理的方法是添加一个方法(例如destroy
),然后在应用程序不再需要该对象时调用它。 - jacobq
obj.destruct()
。 - James M. Lay