Sub topic 4
Creating a WeakRef and Calling deref()
This chapter assumes you know how JavaScript objects and references work, that you are comfortable with closures, and that you can run scripts in Node.js or a browser console. The previous chapters covered reachability and the difference between strong and weak references. Here you put that model to work with the WeakRef API.
The Constructor
A WeakRef is an object that holds a weak reference to one target. The target can still be collected if nothing else holds it strongly. You create one with new:
let target = { name: 'large object' };
const ref = new WeakRef(target);The constructor takes one argument, and it must be a value that can be held weakly. Passing a primitive such as a number or string throws a TypeError. The chapter "What Can Be a Weak Target" lists the exact rules. Calling WeakRef() without new also throws.
A WeakRef has no setter. You cannot point an existing WeakRef at a different object. If you need a new target, create a new WeakRef.
Reading the Target with deref()
deref() is the only method on a WeakRef. It returns the target if the target still exists, and undefined if the garbage collector has reclaimed it. Every read must handle both outcomes:
let target = { name: 'large object' };
const ref = new WeakRef(target);
const obj = ref.deref();
if (obj !== undefined) {
console.log(obj.name);
} else {
console.log('Target was garbage collected');
}
target = null; // the WeakRef alone does not keep the object aliveOnce target is set to null, the only remaining path to the object is the weak one. At some unspecified later time, ref.deref() may start returning undefined. After that it never returns the object again.
Working Model: Dereference Late, Hold Briefly
The usual approach is to call deref() right before you need the object, store the result in a local variable, and let that variable go out of scope soon.
function describe(ref) {
const obj = ref.deref();
if (obj === undefined) return 'gone';
return `still here: ${obj.name}`;
}
const ref = new WeakRef({ name: 'cache entry' });
console.log(describe(ref));The local obj is a strong reference. While it is in scope, the object cannot be collected. That is what you want for the duration of one operation. A target returned by deref() also stays alive until the end of the current job. A later chapter covers that rule.
Common Errors
| Mistake | Why it breaks |
|---|---|
| Calling `ref.deref().name` without a check | Throws `TypeError` once the target is collected |
| Calling `deref()` twice and assuming both results match | The target can be collected between jobs, so the two calls may differ |
| Storing the `deref()` result in a long-lived variable or property | Creates a strong reference, so the `WeakRef` no longer serves any purpose |
| Expecting `undefined` right after dropping the last strong reference | Collection timing is up to the engine and may never happen |
Exercise
A module stores this.current = this.ref.deref() in its constructor and reads this.current from then on. What goes wrong, and how should it be fixed?
Show answer
this.current is a strong reference that lives as long as the module instance, so the target can never be collected and the WeakRef has no effect. Remove the stored property. Call this.ref.deref() each time the object is needed, and handle the undefined case.
Exercise
Write a function withTarget(ref, fn) that calls fn with the target if it exists and returns null otherwise.
Show answer
function withTarget(ref, fn) { const obj = ref.deref(); return obj === undefined ? null : fn(obj); }