我的理解WeakMap
是“对集合中对象的引用被弱保存。如果没有对存储在 WeakMap 中的对象的其他引用,它们可以被垃圾收集。”
为什么在删除引用后,WeakMap 中仍会出现以下键/值对?WeakMap 不应该为空吗?
let dog1 = {name: 'Snickers'};
let dog2 = {name: 'Sunny'};
var strong = new Map();
var weak = new WeakMap();
strong.set(dog1, 'Snickers is the best!');
strong.set(dog2, 'Sunny is the 2nd best!');
weak.set(dog1, 'Snickers is the best!');
weak.set(dog2, 'Sunny is the 2nd best!');
dog1 = null;
dog2 = null;
console.log(strong);
console.log(weak);
/*
Output
Map(2) {{…} => "Snickers is the best!", {…} => "Sunny is the 2nd best!"}
WeakMap {{…} => "Snickers is the best!", {…} => "Sunny is the 2nd best!"}
*/
setTimeout(function(){
console.log("1200ms later... waiting for garbarge collection");
console.log(strong);
console.log(weak);
}, 1200);
/*
Output
Map(2) {{…} => "Snickers is the best!", {…} => "Sunny is the 2nd best!"}
WeakMap {{…} => "Snickers is the best!", {…} => "Sunny is the 2nd best!"}
*/