简体   繁体   中英

How to imitate garbage collection in javascript?

Let's say I have a library that keeps an array of objects, the purpose is not really relevant to the issue. it looks like this:

window.Tracker = {
  objects: [],
  track: function(obj){
    this.objects.push(obj)
  }
}

In other parts of the app, Vue/React components constantly push objects to this library as they're loaded from a server:

this.movie = { id: 56456, name: "Avengers" }
Tracker.track(this.props.movie)

Overtime, the Tracker.objects array gets bigger and bigger, mostly because of objects no longer needed (their components no longer exist), and I really don't want to keep objects like this in the array.

The problem is I don't have control over anything aside from this Tracker library. (so I can't really make callbacks when the object is no longer needed)

But I need a way to garbage collect/ get rid of objects that are no longer used by anything other than in the Tracker.objects array.

Is this possible?

The only way to store objects in a collection so that they are still garbage collected are WeakMaps. However you can't iterate them:

Because of references being weak, WeakMap keys are not enumerable (ie there is no method giving you a list of the keys). If they were, the list would depend on the state of garbage collection, introducing non-determinism. ~ MDN

So no, this is not possible in js for good reasons.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM