我刚刚读到WeakMaps通过专门使用对象作为键来利用垃圾收集,并且将对象赋值为null等同于删除它:
let planet1 = {name: 'Coruscant', city: 'Galactic City'};
let planet2 = {name: 'Tatooine', city: 'Mos Eisley'};
let planet3 = {name: 'Kashyyyk', city: 'Rwookrrorro'};
const lore = new WeakMap();
lore.set(planet1, true);
lore.set(planet2, true);
lore.set(planet3, true);
console.log(lore); // output: WeakMap {{…} => true, {…} => true, {…} => true}
然后我将对象设置为null:
planet1 = null;
console.log(lore); // output: WeakMap {{…} => true, {…} => true, {…} => true}
为什么输出相同?它应该被删除,以便gc可以重用之前在应用程序中占用的内存吗?我将不胜感激任何澄清。谢谢!