不耐烦的程序员的 JavaScript(ES2022 版)
请支持此书:购买捐赠
(广告,请不要屏蔽。)

36 非参照集合(WeakSet)(高级)



非参照集合与集合类似,但具有以下不同点

鉴于我们无法迭代其元素,因此非参照集合的用例不多。它们确实使我们能够标记对象。

36.1 示例:将对象标记为安全,以便使用一个方法

以下代码演示了如何通过一个类确保只有它创建的实例才能应用自己的方法(基于 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 非参照集合 API

构造函数和 `WeakSet` 的三个方法的工作原理与 它们的 `Set` 等价物 相同