Creating a regular weak-reference in Javascript us

2020-02-01 00:54发布

问题:

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.