Please support this book: buy it or donate

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:

  1. const foos = new WeakSet();
  2. class Foo {
  3. constructor() {
  4. foos.add(this);
  5. }
  6. method() {
  7. if (!foos.has(this)) {
  8. throw new TypeError('Incompatible object!');
  9. }
  10. }
  11. }
  12. const foo = new Foo();
  13. foo.method(); // works
  14. assert.throws(
  15. () => {
  16. const obj = {};
  17. Foo.prototype.method.call(obj); // throws an exception
  18. },
  19. TypeError
  20. );

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]