33. WeakSets (WeakSet)
WeakSets are similar to Sets, with the following differences:
They can hold objects, without preventing those objects from being garbage-collected.
They are black boxes: You only get any data out of a WeakSet if you have both the WeakSet and a value. The only methods that are supported are
.add()
,.delete()
,.has()
. Consult the section on WeakMaps as black boxes for an explanation of why WeakSets don’t allow iteration, looping and clearing.
Given that you can’t iterate over their elements, there are not that many use cases for WeakSets. They do enable you to mark objects.
33.1. Example: Marking objects as safe to use with a method
Domenic Denicola shows how a class Foo
can ensure that its methods are only applied to instances that were created by it:
const foos = new WeakSet();
class Foo {
constructor() {
foos.add(this);
}
method() {
if (!foos.has(this)) {
throw new TypeError('Incompatible object!');
}
}
}
const foo = new Foo();
foo.method(); // works
assert.throws(
() => {
const obj = {};
Foo.prototype.method.call(obj); // throws an exception
},
TypeError
);
33.2. WeakSet API
The constructor and the three methods of WeakSet
work the same as their Set
equivalents:
new WeakSet<T>(values?: Iterable<T>)
[ES6].add(value: T): this
[ES6].delete(value: T): boolean
[ES6].has(value: T): boolean
[ES6]