Will a “circular” link be considered “reachable” for WeakMap?

function f() { const w = new WeakMap(); const o = {}; w.set(o, { v: o }); return w; } const weakMap = f(); 

For this code, could only weakMap be considered accessible or not? Therefore, will it be garbage collection or not?

PS: This question is asked from the point of view of the specification, and not with specific implementations.

+6
source share
1 answer

Quote WeakMap Section ,

If the object that is used as the key of the WeakMap key / value pair is accessible only through the chain of links that begins with this WeakMap, then this key / value pair is unavailable and is automatically deleted from WeakMap.

In your case, the only way to achieve o is to start with one of the keys in WeakMap , since there are no external links to it. Therefore, it will be deemed unavailable.

WeakMap implementations should detect and remove such key / value pairs and any associated resources.

So this will be the ultimate garbage collection.

+8
source

All Articles