[英]Best way implement destructor in JS
考慮下面的代碼
class Hello {
constructor(name) {
this.interval = setInterval(() => {
console.log('===', name)
}, 1000)
}
destroy() {
clearInterval(this.interval)
}
}
let h = new Hello('aaa')
// h.destory()
h = new Hello('bbb')
如果構造函數分配了一些資源,則在哪里釋放資源? 據我目前的理解,當h
被重新分配給new Hello('bbb')
到持有new Hello('aaa')
內存時,應該由GC釋放。
這是一個好習慣, new
與destroy
new
應該成對出現嗎?
不幸的是(我相信)沒有辦法捕獲對象的垃圾回收來執行某些操作。 相反,您需要通過明確顯示創建/刪除內容來構建自己的管理,以清理計時器等資源。 我知道您的示例是一個玩具,但是您不能簡單地按照顯示的方式重新分配。 您需要執行以下操作:
const objects = {}
const createObject = name => {
const obj = new Hello(name)
objects[name] = obj
return obj
}
const deleteObject = name => {
objects[name].destroy()
delete objects[name]
}
let h = createObject('aaa')
deleteObject('aaa') // interval cleared but not gc'd because of h
h = createObject('bbb') // all references to aaa now gone
顯然,這是一個簡單的示例,並且將根據您的需求采用更優雅的方法來完成此操作,但希望您能理解。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.