JavaScript for impatient programmers (beta)
Please support this book: buy it or donate
(Ad, please don’t block.)

33 WeakSets (WeakSet)



WeakSets are similar to Sets, with the following differences:

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: