ECMAScript 6类析构函数 [英] ECMAScript 6 class destructor
问题描述
例如,如果我将一些我的对象的方法作为事件监听器构造函数,当我的对象被删除时,我想删除它们。
一个解决方案是创建一个 desctructor
方法为每个类需要这种行为和手动调用它。这将删除对事件处理程序的引用,因此我的对象将真正准备好进行垃圾回收。否则它会留在内存中,因为这些方法。
但是我希望ECMAScript 6具有本机的东西,将在对象被垃圾回收之前被调用。 / p>
如果没有这样的机制,这些问题的模式/约定是什么?
有没有像ECMAScript 6的析构函数这样的东西?
否。 EcmaScript 6没有指定任何垃圾收集语义,所有的 [1] ,所以没有什么像破坏。
如果我在构造函数中注册了一些我的对象的方法作为事件监听器,那么当我的对象被删除时,我想删除它们
一个析构函数甚至不会帮助你。事件侦听器本身仍然引用您的对象,因此在取消注册之前无法收集垃圾。
您实际寻找的是一种注册侦听器而不将其标记为活根对象(请咨询您当地的事件来源制造商获得这样一个功能)。
1):嗯,有一个起始于 WeakMap
和< a href =http://www.ecma-international.org/ecma-262/6.0/#sec-weakset-objects =nofollow noreferrer> WeakSet
对象。但是,真正的弱引用仍然存在于 [1] < a href =http://wiki.ecmascript.org/doku.php?id=strawman:weak_refs =nofollow noreferrer> [2] 。
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 desctructor
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.
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?
Is there such a thing as destructors for ECMAScript 6?
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): Well, there is a beginning with the specification of WeakMap
and WeakSet
objects. However, true weak references are still in the pipeline [1][2].
这篇关于ECMAScript 6类析构函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!