Firefox JavaScript chrome代码中的弱引用 [英] Weak reference in Firefox JavaScript chrome code

查看:129
本文介绍了Firefox JavaScript chrome代码中的弱引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在基于Jetpack的库(即我们正在讨论的chrome /扩展代码)中写一个类 A

$ $ $ $



$ b $
//班级成员
};

用户创建一个类 A

  var a = new A(); 

现在假设我想跟踪所有 A 创建的,我可以这样做:

pre $ var listA = [];

并添加 listA.push(this); A 的构造函数中,结束于:

  var listA = []; 

函数A(){
//构造函数
listA.push(this);
}

A.prototype = {
//类成员
};

一切正常,直到 a 删除其引用(例如 a 超出范围)。我现在有一个问题: listA 仍然包含对 a 的引用,所以它永远不会被垃圾收集。此外,我无法过滤 listA A 实例,否则无法访问。我有效地泄漏内存。

我需要推送到 listA 弱引用,而不是常规那些。我认为有可能做到这一点,但我真的不知道从哪里去。我可以这样想:

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

但是我不知道如何测试弱引用是否仍然有效。或者如何有效地过滤掉 listA 中的无效条目。任何建议?

解决方案

你只需要让你的课程表示它支持弱引用。然后,当你想使用它的弱引用版本时,你需要使用 Components.utils.getWeakReference 并保存。 以下是一些测试代码它向你展示了如何在JavaScript中使用它。


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?

解决方案

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.

这篇关于Firefox JavaScript chrome代码中的弱引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆