You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript(ES6):将对象设为null时WeakMap的垃圾回收机制

Understanding JavaScript WeakMap: Keys, Garbage Collection, and Object References

Hey folks, let's break down how JavaScript's WeakMap works—focusing on its key rules, how it taps into garbage collection, and why setting an object to null effectively removes its presence from a WeakMap context.

Core WeakMap Characteristics

  • Only objects allowed as keys: Unlike regular Map, WeakMap refuses primitive values (strings, numbers, booleans) as keys. This restriction is what enables its unique garbage collection behavior.
  • Weak references to keys: WeakMap holds weak references to its object keys. In plain terms: if the object key has no other strong references left in your code, the JavaScript garbage collector will automatically clean up that object—and also delete the corresponding key-value pair from the WeakMap. No manual cleanup needed, which makes it ideal for use cases like caching or storing private object metadata.

Why Setting an Object to null Acts Like Deletion

When you assign an object variable to null, you're severing the strong reference to that object. If no other variables or parts of your code are pointing to it, the garbage collector will mark the object for cleanup. Once that happens, the WeakMap will drop the associated key-value pair automatically—you don't have to call delete() on the WeakMap yourself.

Example Code

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}

// Remove the strong reference to planet1
planet1 = null;
// After garbage collection runs, lore will no longer include the planet1 entry

内容的提问来源于stack exchange,提问作者Bruno Mazza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:56:00