As I understand it, with JavaScript weak maps, when an object used as a key has no remaining references to it, it is garbage collected (or at least slated for garbage collection) and removed from the weak map.
Quoting from javascript.info (emphasis mine):
If we use an object as the key in [the weak map], and there are no other
references to that object – it will be removed from memory (and from
the map) automatically.
However, if I run:
const mymap = new WeakMap();
let myobj = {foo: 'bar'};
mymap.set(myobj, 'etc');
myobj = null;
console.log(mymap);
setTimeout(() => console.log(mymap), 1000); //in case garbage collection is delayed
...when inspected in the console, it still shows the single entry I inserted into it.
Now, I realise there's no programmatical way to retrieve this entry, since I no longer have a reference to the object (and weak maps are not enumerable). But why would I believe it's been removed from the map if the console's still showing it's in there?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…