ECMAScript 6 类析构函数 [英] ECMAScript 6 class destructor

查看:31
本文介绍了ECMAScript 6 类析构函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 ECMAScript 6 有构造函数,但是 ECMAScript 6 有析构函数吗?

I know ECMAScript 6 has constructors but is there such a thing as destructors for ECMAScript 6?

例如,如果我在构造函数中将我的一些对象方法注册为事件侦听器,我想在我的对象被删除时删除它们.

For example if I register some of my object's methods as event listeners in the constructor, I want to remove them when my object is deleted.

一个解决方案是约定为每个需要这种行为的类创建一个析构函数方法并手动调用它.这将删除对事件处理程序的引用,因此我的对象将真正准备好进行垃圾收集.否则它会因为这些方法而留在内存中.

One solution is to have a convention of creating a destructor method for every class that needs this kind of behaviour and manually call it. This will remove the references to the event handlers, hence my object will truly be ready for garbage collection. Otherwise it'll stay in memory because of those methods.

但我希望 ECMAScript 6 是否有一些原生的东西可以在对象被垃圾收集之前被调用.

But I was hoping if ECMAScript 6 has something native that will be called right before the object is garbage collected.

如果没有这样的机制,那么针对此类问题的模式/约定是什么?

If there is no such mechanism, what is a pattern/convention for such problems?

推荐答案

ECMAScript 6 有没有析构函数这样的东西?

Is there such a thing as destructors for ECMAScript 6?

没有.EcmaScript 6 根本没有指定任何垃圾收集语义[1],所以也没有什么比破坏"更像了.

No. EcmaScript 6 does not specify any garbage collection semantics at all[1], so there is nothing like a "destruction" either.

如果我在构造函数中将我的一些对象方法注册为事件监听器,我想在我的对象被删除时删除它们

If I register some of my object's methods as event listeners in the constructor, I want to remove them when my object is deleted

析构函数在这里也帮不了你.事件侦听器本身仍然引用您的对象,因此在它们被取消注册之前将无法被垃圾收集.
您实际上正在寻找的是一种注册侦听器而不将它们标记为活动根对象的方法.(向您当地的事件源制造商咨询此类功能).

A destructor wouldn't even help you here. It's the event listeners themselves that still reference your object, so it would not be able to get garbage-collected before they are unregistered.
What you are actually looking for is a method of registering listeners without marking them as live root objects. (Ask your local eventsource manufacturer for such a feature).

1): 嗯,有一个开头是 WeakMapWeakSet 对象.然而,真正的弱引用仍在处理中[1][2].

这篇关于ECMAScript 6 类析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆