简体   繁体   English

JS中实现析构函数的最佳方法

[英]Best way implement destructor in JS

Consider the code below 考虑下面的代码

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')

If the constructor allocate some resource, where to release the resource? 如果构造函数分配了一些资源,则在哪里释放资源? As far as I current understanding, when h is re-assigned to new Hello('bbb') to memory holding new Hello('aaa') should be released by GC . 据我目前的理解,当h被重新分配给new Hello('bbb')到持有new Hello('aaa')内存时,应该由GC释放。

Is this a good convention that new and destroy should come in pair? 这是一个好习惯, newdestroy new应该成对出现吗?

Unfortunately there is no way (i believe) to catch the garbage collection of an object to perform some action. 不幸的是(我相信)没有办法捕获对象的垃圾回收来执行某些操作。 Instead you need to build your own management for cleaning up resources like timers, etc. by making your creations/removals explicit. 相反,您需要通过明确显示创建/删除内容来构建自己的管理,以清理计时器等资源。 I know your example is a toy, but you can't simply reallocate in the way you have shown. 我知道您的示例是一个玩具,但是您不能简单地按照显示的方式重新分配。 You need to do something like: 您需要执行以下操作:

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

Obviously this is a simple example, and there will be more elegant ways to do it depending on your needs, but hopefully you get the idea. 显然,这是一个简单的示例,并且将根据您的需求采用更优雅的方法来完成此操作,但希望您能理解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM