Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a regular weak-reference in Javascript using 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.

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?

like image 852
Michael Lorton Avatar asked Apr 03 '15 16:04

Michael Lorton


People also ask

What is WeakSet and WeakMap in JavaScript?

WeakMap is Map -like collection that allows only objects as keys and removes them together with associated value once they become inaccessible by other means. WeakSet is Set -like collection that stores only objects and removes them once they become inaccessible by other means.

What is the use of WeakSet in JS?

WeakSet in JavaScript is used to store a collection of objects. It adapts the same properties of that of a set i.e. does not store duplicates. The major difference of a WeakSet with the set is that a WeakSet is a collection of objects and not values of some particular type.

What is WeakRef JS?

A WeakRef object contains a weak reference to an object, which is called its target or referent. A weak reference to an object is a reference that does not prevent the object from being reclaimed by the garbage collector. In contrast, a normal (or strong) reference keeps an object in memory.

When would you use a WeakMap?

Whenever you want to extend an object but can't because it is sealed - or from an external source - a WeakMap can be applied. A WeakMap is a map (dictionary) where the keys are weak - that is, if all references to the key are lost and there are no more references to the value - the value can be garbage collected.


1 Answers

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.

like image 170
Bergi Avatar answered Oct 22 '22 06:10

Bergi