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?
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