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

36 WeakSets (WeakSet) (advanced)



WeakSets are similar to Sets, with the following differences:

Given that we can’t iterate over their elements, there are not that many use cases for WeakSets. They do enable us to mark objects.

36.1 Example: Marking objects as safe to use with a method

The following code demonstrates how a class can ensure that its methods are only applied to instances that were created by it (based on code by Domenic Denicola):

const instancesOfSafeClass = new WeakSet();

class SafeClass {
  constructor() {
    instancesOfSafeClass.add(this);
  }

  method() {
    if (!instancesOfSafeClass.has(this)) {
      throw new TypeError('Incompatible object!');
    }
  }
}

const safeInstance = new SafeClass();
safeInstance.method(); // works

assert.throws(
  () => {
    const obj = {};
    SafeClass.prototype.method.call(obj); // throws an exception
  },
  TypeError
);

36.2 WeakSet API

The constructor and the three methods of WeakSet work the same as their Set equivalents: