企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 33\. WeakSets(`WeakSet`) > 原文: [http://exploringjs.com/impatient-js/ch_weaksets.html](http://exploringjs.com/impatient-js/ch_weaksets.html) WeakSets 与 Sets 类似,但有以下区别: * 它们可以保存对象,而不会阻止这些对象被垃圾收集。 * 它们是黑盒子:如果你同时拥有 WeakSet 和一个值,你只能从 WeakSet 中获取任何数据。支持的唯一方法是`.add()`,`.delete()`,`.has()`。有关为什么 WeakSets 不允许迭代,循环和清除的原因,请参考 [WeakMaps 部分作为黑盒](ch_weakmaps.html#weakmaps-as-black-boxes)。 鉴于您无法迭代其元素,WeakSets 的用例并不多。它们可以让您标记对象。 ### 33.1。示例:将对象标记为可以安全使用方法 [Domenic Denicola 显示](https://mail.mozilla.org/pipermail/es-discuss/2015-June/043027.html)类`Foo`如何确保其方法仅应用于由它创建的实例: ```js 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 `WeakSet`的构造函数和三种方法与[的`Set`等价物](ch_sets.html#quickref-sets)的作用相同: * `new WeakSet<T>(values?: Iterable<T>)` <sup>[ES6]</sup> * `.add(value: T): this` <sup>[ES6]</sup> * `.delete(value: T): boolean` <sup>[ES6]</sup> * `.has(value: T): boolean` <sup>[ES6]</sup>