HomepageExploring JavaScript (ES2024 Edition)
You can support this book: buy it or donate
(Ad, please don’t block.)

38 WeakSets (WeakSet) [ES6] (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.

38.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
);

38.2 WeakSet API

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