0

I want to store a weak reference to an object in Javascript. I'm trying to implement a cache, and to avoid memory leaks I don't want to hold any strong references. I would use WeakMap or WeakSet, but those do not allow me to retrieve objects after they are inserted, defeating the purpose of a cache.

Is there any way to implement a "normal" weak reference in Javascript? Is there a work around I could use in my cache to avoid leaking memory?

Edit: See the duplicate question.

I ended up just using normal references and periodically emptying the cache to deal with memory leaks. Not a great solution, but that's Javascript for you...

drdrez
  • 921
  • 1
  • 7
  • 16
  • _"but those do not allow me to retrieve objects after they are inserted"_ umm WeakMap does, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/get – Patrick Evans Jan 06 '17 at 01:16
  • @PatrickEvans The get method doesn't help me. I want to get the weak references out of the collection, but the get method requires you to already have a reference, and pass it in as an argument to extract a different value. – drdrez Jan 06 '17 at 03:01
  • use `WeakMaps` if you only need to retrieve/set. If you want to iterate through a weak array, then that is not currently possible in javascript. – Jack G Jul 16 '17 at 15:38

0 Answers0