3

I've came across this WeakRef polyfill: ungap / weakrefs.

I'm struggling to understand how it works, particularly at line 11-14:

var wr = new WeakMap;
function WeakRef(value) {
    wr.set(this, value);
}

So there is a global WeakMap wr.

And a constructor-like function WeakRef that takes a value and stores it in wr, using this (the resulting object) as key.

My understanding is the wr global WeakMap wouldn't drop the inserted value until the key is dropped. In this case, the key is the resulting WeakRef object.

So value wouldn't be allowed to be GC-ed until the created WeakRef is dropped.

Wouldn't this make the polyfill a strong reference?

wisha
  • 643
  • 1
  • 6
  • 12
  • 1
    It would; your understanding is correct. There's no way to polyfill weak references until the [WeakRef proposal](https://github.com/tc39/proposal-weakrefs) – FZs Jan 31 '21 at 08:23
  • 2
    Yep. It is strong reference. How can they call this a polyfill. It's a stub. – wisha Jan 31 '21 at 08:27
  • Does this answer your question? [Why are WeakRef polyfills made with WeakMap? I don't see how that can work](https://stackoverflow.com/questions/64140647/why-are-weakref-polyfills-made-with-weakmap-i-dont-see-how-that-can-work) – user3840170 Nov 14 '21 at 19:49

1 Answers1

3

It really is strong reference.

Why couldn't they just mention that in the README. Or maybe atleast leave the issue mentioning this open??

wisha
  • 643
  • 1
  • 6
  • 12