我正在体验JavaScript弱映射,在控制台中尝试这段代码后,运行了--js-标志=--公开-gc“,我不明白为什么弱映射会继续引用a.b,如果是gc‘’ed的话。
var a = {listener: function(){ console.log('A') }}
a.b = {listener: function(){ console.log('B') }}
var map = new WeakMap()
map.set(a.b, [])
map.set(a, [a.b.listener])
console.log(map) // has both a and a.b
gc()
console.log(map) // still have both a and a.b
a = undefined
gc()
console.log(map) // only have a.b: why does still have a reference to a.b? Should'nt be erased?发布于 2017-04-24 04:16:00
更新2/2020
当我现在运行这段代码时,它就像预期的那样工作。我认为打开控制台会导致Chrome早期版本中的对象被保存,但现在不行。重新分配保存对对象的引用的变量的值将导致该对象被垃圾收集(假设其他任何对象都没有引用)。
在示例代码中,您没有释放a变量。它是一个顶级变量,它从不超出作用域,也不会显式地取消引用,因此它保留在WeakMap中。一旦代码中没有对对象的引用,WeakMap/WeakSet就会释放对象。在您的示例中,如果您在一个console.log(a)调用之后使用gc(),那么您仍然希望a还活着,对吗?
下面是一个工作示例,展示了WeakSet的作用以及一旦所有对它的引用都消失了,它将如何删除一个条目:https://embed.plnkr.co/cDqi5lFDEbvmjl5S19Wr/
const wset = new WeakSet();
// top level static var, should show up in `console.log(wset)` after a run
let arr = [1];
wset.add(arr);
function test() {
let obj = {a:1}; //stack var, should get GCed
wset.add(obj);
}
test();
//if we wanted to get rid of `arr` in `wset`, we could explicitly de-reference it
//arr = null;
// when run with devtools console open, `wset` always holds onto `obj`
// when devtools are closed and then opened after, `wset` has the `arr` entry,
// but not the `obj` entry, as expected
console.log(wset);请注意,打开Chrome工具可以阻止一些对象收集垃圾,这使得在实际操作中看到这一点比预期的困难得多:)
https://stackoverflow.com/questions/38203446
复制相似问题