Creating a regular weak-reference in Javascript using WeakMaps

不打扰是莪最后的温柔 提交于 2019-11-26 21:13:14

问题


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.

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.

Is this possible to use WeakMaps in some clever way I haven't thought of to do this?


回答1:


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.

Real weak references might come with ES8, see here and there for drafts.



来源:https://stackoverflow.com/questions/29436056/creating-a-regular-weak-reference-in-javascript-using-weakmaps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!