Memory-sensitive caches
Cache large objects without making the cache a strong owner of their memory.
JavaScript · Class
WeakRef provides a non-owning reference to an object or non-registered symbol, so the target may be garbage-collected. Use deref() to retrieve the target when it is still available; garbage-collection timing is nondeterministic.
WeakRef holds a non-owning reference to an object or non-registered symbol. Calling deref() retrieves the target while it remains available, or returns undefined after garbage collection; collection timing is nondeterministic.
new WeakRef(target)| Name | Type | Description |
|---|---|---|
target | object | symbol | The value to reference; it must be an object or a non-registered symbol. |
A new WeakRef object referring to the supplied target; deref() returns the target or undefined if it has been reclaimed.
const target = {name: "Ada"};
const ref = new WeakRef(target);
const value = ref.deref();
if (value) {
console.log(value.name);
}Creates a weak reference and safely uses the target only when dereferencing still returns it.
Cache large objects without making the cache a strong owner of their memory.
Track optional objects such as DOM nodes without preventing their collection.
Access a resource only while its target remains alive, with a fallback when deref() returns undefined.
WeakRef()WeakRef.prototype.deref()FinalizationRegistryWeakMapWeakSet