问题描述
我正在尝试使用WeakMaps做明确的事情:我想创建一个弱引用。特别是,我想列出一个没有影响听众生活的列表的事件监听器。
I am trying to do the obvious thing with WeakMaps: I want to create a weak reference. In particular, I want to have a list of event-listeners without that list influencing the life of the listener.
所以我很高兴找到WeakMaps,直到我看到它们仅用于满足一个(相当罕见的)用例,扩展另外密封的对象。我无法想到,当我想要这样做,但我需要所有的听众列表。
So I was very excited to find WeakMaps, until I saw they were only built to satisfy one (fairly rare) use-case, extending objects that were otherwise sealed. I can't think when I ever wanted to do that, but I need lists of listeners all the time.
这可能是以一些聪明的方式使用WeakMaps我避风港不想这样做?
Is this possible to use WeakMaps in some clever way I haven't thought of to do this?
推荐答案
不,使用WeakMaps创建弱引用是不可能的。 WeakMaps是不可迭代的,使用它们总是需要密钥。这是一个故意的决定(也),所以垃圾收集不会影响你的程序的语义 - 这正是你想要什么。
No, it is impossible to use WeakMaps to create a weak reference. WeakMaps are not iterable, to use them you always need the key. This was a deliberate decision (also here), so that garbage collection does not influence the semantics of your program - which is exactly what you want.
真正的弱引用可能与ES8一起出现,请参阅和草稿。
Real weak references might come with ES8, see here and there for drafts.
这篇关于使用WeakMaps在Javascript中创建常规弱引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!