Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Weak reference in Firefox JavaScript chrome code

Suppose I'm writing a class A in my Jetpack-based library (i.e. we're talking about chrome/extension code):

function A() {
  //constructor
}
A.prototype = {
  //class members
};

The user creates an instance of class A:

var a = new A();

now suppose I want to keep track of all the instances of A that were created, I could do:

var listA = [];

and add listA.push(this); in the constructor of A, ending up with:

var listA = [];

function A() {
  // constructor
  listA.push(this);
}

A.prototype = {
  // class members
}; 

all is fine, until the user of a drops its reference (e.g. a goes out of scope). I have now a problem: listA still contains a reference to a so it will never be garbage collected. Moreover I have no way to filter out of listA instances of A that are otherwise unreachable. I'm effectively leaking memory.

What I'd need is to push to listA weak references instead of regular ones. I think it is possible to do it somehow, but I don't really know where to go from here. I can envision something like:

var weak_a = new weakRef(a);
assert(weak_a.ref === a);

But then I don't know, for example, how to test if a weak reference is still valid. Or how to efficiently filter out dead weak entries in listA. Any suggestions?

like image 424
CAFxX Avatar asked Oct 25 '22 19:10

CAFxX


1 Answers

You just need to make your class indicate it supports weak references. Then, when you want to use the weak reference version of it, you'll want to use Components.utils.getWeakReference and store that. Here is some test code that shows you how to use it more in JavaScript.

like image 151
sdwilsh Avatar answered Oct 27 '22 10:10

sdwilsh