WeakMap Attaches Metadata Without Leaks
Attach per-object metadata through a WeakMap keyed by the object itself, so entries vanish with the key and the map cannot be enumerated.
Code
// WeakMap: 以对象为键挂元数据,不阻止键对象被 GC 回收
const viewState = new WeakMap();
function track(node) {
if (!viewState.has(node)) viewState.set(node, { visits: 0 });
viewState.get(node).visits += 1;
return viewState.get(node).visits;
}
const row = { id: 'row-1' };
const another = { id: 'row-1' }; // 内容相同但是不同对象
console.log(track(row), track(row));
console.log('same object:', viewState.get(row) === viewState.get(row));
console.log('different object has state:', viewState.has(another));
// WeakMap 不可枚举:拿不到所有键,这正是"跟随对象生命周期"的代价
console.log('size property:', viewState.size === undefined);Output
Captured from a sandboxed run of this snippet in the build pipeline.
1 2
same object: true
different object has state: false
size property: trueHow it works
WeakMap Attaches Metadata Without Leaks reduces to the function track.
Applying it
The main signature reads function track(node)
The demo output is labeled (same object:, different object has state:, size property:), so every printed line maps back to its originating operation.
Statements that matter
return viewState.get(node).visits;
viewState.get(node).visits += 1;
Interactive Tools for This Topic
Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.YAML Frontmatter ExtractorExtract the YAML frontmatter block from Markdown documents and parse scalars and simple lists into a JSON metadata object.
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. The file defines `track` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.