Firefox JavaScript chrome代码中的弱引用 [英] Weak reference in Firefox JavaScript chrome code
问题描述
A
:: $ $ $ $
$ b $
//班级成员
};
用户创建一个类 A
:
var a = new A();
现在假设我想跟踪所有 并添加 一切正常,直到 我需要推送到 但是我不知道如何测试弱引用是否仍然有效。或者如何有效地过滤掉 你只需要让你的课程表示它支持弱引用。然后,当你想使用它的弱引用版本时,你需要使用 Suppose I'm writing a class The user creates an instance of class now suppose I want to keep track of all the instances of and add all is fine, until the user of What I'd need is to push to 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 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 这篇关于Firefox JavaScript chrome代码中的弱引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋! 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中使用它。A
in my Jetpack-based library (i.e. we're talking about chrome/extension code):function A() {
//constructor
}
A.prototype = {
//class members
};
A
:var a = new A();
A
that were created, I could do:var listA = [];
listA.push(this);
in the constructor of A
, ending up with:var listA = [];
function A() {
// constructor
listA.push(this);
}
A.prototype = {
// class members
};
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.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);
listA
. Any suggestions?Components.utils.getWeakReference
and store that. Here is some test code that shows you how to use it more in JavaScript.