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.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
// 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: true

How 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

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.