Weak references
WeakRef はオブジェクトへの弱い参照を作成し、ガベージコレクションを妨げません。FinalizationRegistry でオブジェクトの回収時にクリーンアップ処理を実行できます。
概要
WeakRef はオブジェクトへの弱い参照を作成し、ガベージコレクションを妨げません。FinalizationRegistry でオブジェクトの回収時にクリーンアップ処理を実行できます。
対応ブラウザ
| 機能 | デスクトップ | モバイル | ||||
|---|---|---|---|---|---|---|
| Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS | |
| 84 | 84 | 79 | 14.1 | 84 | 14.5 | |
| FinalizationRegistry コンストラクターは、指定されたコールバックを使用する FinalizationRegistry オブジェクトを生成します。 | 84 | 84 | 79 | 14.1 | 84 | 14.5 |
| register() メソッドはオブジェクトを FinalizationRegistry インスタンスへ登録し、オブジェクトがガベージコレクションで回収された場合、レジストリのコールバックが呼び出されるようになります。 | 84 | 84 | 79 | 14.1 | 84 | 14.5 |
FinalizationRegistry.register.symbol as target 未登録シンボルをターゲットとする | 109 | 109 | 146 | 16.4 | 109 | 16.4 |
| unregister は対象のオブジェクトを FinalizationRegistry インスタンスから登録解除します。 | 84 | 84 | 79 | 14.1 | 84 | 14.5 |
FinalizationRegistry.unregister.symbol as target 未登録シンボルをターゲットとする | 109 | 109 | | 16.4 | 109 | 16.4 |
| その他 | ||||||
| WeakRef オブジェクトは、ガベージコレクションを受けることを妨げない他のオブジェクトへの弱い参照を保持します。 | 84 | 84 | 79 | 14.1 | 84 | 14.5 |
| ビルトインオブジェクト | ||||||
| WeakRef() コンストラクターは、 WeakRef オブジェクトを生成します。 | 84 | 84 | 79 | 14.1 | 84 | 14.5 |
WeakRef.WeakRef.symbol as target 未登録シンボルをターゲットとする | 109 | 109 | 146 | 16.4 | 109 | 16.4 |
| deref() は WeakRef インスタンスのメソッドで、この WeakRef のターゲット値、またはその値が既にガベージコレクションされている場合は undefined を返します。 | 84 | 84 | 79 | 14.1 | 84 | 14.5 |
基本構文
let target = { data: 'important' };
const ref = new WeakRef(target);
ref.deref(); // { data: 'important' }
target = null; // Becomes a candidate for garbage collection
// ref.deref(); // undefined (after garbage collection) ライブデモ
Create and dereference a WeakRef
Wrap an object in WeakRef and inspect the current dereferenced value.
Use WeakRef in a cache
Keep a lightweight reference in a cache without forcing long-term retention.
Compare direct objects and WeakRef
See the difference between the original object and its weak reference wrapper.
実務での使いどころ
-
Weak references の活用
オブジェクトへの弱い参照を保持する WeakRef と、クリーンアップコールバックの FinalizationRegistry。
注意点
- 特になし。すべての主要ブラウザで安定して動作する。
アクセシビリティ
- JavaScript による動的更新時は、aria-live リージョンで変更をスクリーンリーダーに通知する。
参考リンク
Powered by web-features