WeakRef Deref Survives Until GC Runs

Hold objects weakly with WeakRef and observe collection via FinalizationRegistry: deref may still return the object until GC actually reclaims it.

JavascriptResilience

Code

javascriptsnippet
19 lines
let target = { page: 'report.pdf' };

// WeakRef 包住对象:不阻止回收,持有期间 deref 返回原对象
const ref = new WeakRef(target);
console.log('alive :', ref.deref() === target);

// FinalizationRegistry 在对象被回收时收到回调,用于外部资源 cleanup
const registry = new FinalizationRegistry((token) => {
  console.log('collected:', token);
});
const token = Symbol('release');
registry.register(target, token, token);

// unregister 返回 true:在 GC 发生前撤回监听,回调不会再触发
console.log('unregistered:', registry.unregister(token));

// 释放强引用;GC 何时运行不确定,deref 可能已返回 undefined
target = null;
console.log('deref type:', typeof ref.deref());

Output

Captured from a sandboxed run of this snippet in the build pipeline.

alive : true
unregistered: true
deref type: object

How the snippet works

Top-level bindings target, ref, registry, token hold the demo state — nothing sits inside a function scope.

One object literal carries page — every value is written inline.

Using it

The demo output is labeled (alive :, unregistered:, deref type:); each label names the call that printed it.

Key statements

const registry = new FinalizationRegistry((token) => {
  console.log('collected:', token);
});

Interactive Tools for This Topic

FAQ

Which packages does this snippet need?
None. Every symbol the code uses resolves inside the standard library. Its state lives in module-level bindings: `target`, `ref`, `registry`.