new WeakSet()
WeakSet
对象允许你将
弱保持对象
存储在一个集合中。
语法
new WeakSet([iterable]);
iterable
:如果传入一个可迭代对象作为参数,则该对象的所有迭代值都会被自动添加进生成的
WeakSet
对象中。
描述
WeakSet
对象是一些对象值的集合,并且其中的每个对象值都只能出现一次.
它和
Set
对象的区别有两点:
-
WeakSet
对象中只能存放对象引用,不能存放值,而Set
对象都可以.
-
WeakSet
对象中存储的对象值都是被弱引用的,如果没有其他的变量或属性引用这个对象值,则这个对象值会被当成垃圾回收掉。正因为这样,WeakSet
对象是无法被枚举的,没有办法拿到它包含的所有元素.
实例
const ws = new WeakSet(); const foo = {}; const bar = {}; ws.add(foo); ws.add(bar); ws.has(foo); // true ws.has(bar); // true ws.delete(foo); // removes foo from the set ws.has(foo); // false, foo has been removed ws.has(bar); // true, bar is retained
Note that
foo !== bar
. While they are similar objects,
they are not the same object
. And so they are both added to the set.