WeakSet 对象允许你将弱保持对象存储在一个集合中。
语法
new WeakSet([iterable]);
参数
- iterable
-
如果传入一个
可迭代对象作为参数, 则该对象的所有迭代值都会被自动添加进生成的
WeakSet对象中.
描述
WeakSet 对象是一些对象值的集合, 并且其中的每个对象值都只能出现一次.
它和 Set 对象的区别有两点:
WeakSet对象中只能存放对象引用, 不能存放值, 而Set对象都可以.WeakSet对象中存储的对象值都是被弱引用的, 如果没有其他的变量或属性引用这个对象值, 则这个对象值会被当成垃圾回收掉. 正因为这样,WeakSet对象是无法被枚举的, 没有办法拿到它包含的所有元素.
属性
-
WeakSet.length -
length属性的值为 0. -
WeakSet.prototype -
WeakSet实例的所有继承属性和继承方法都在该对象上.
WeakSet 实例
所有 WeakSet 实例都继承自 WeakSet.prototype.
属性
-
WeakSet.prototype.constructor -
返回构造函数即
WeakSet本身.
方法
-
WeakSet.prototype.add(value) -
在
该
WeakSet对象中添加一个新元素value. -
WeakSet.prototype.clear() -
清空该
WeakSet对象中的所有元素. -
WeakSet.prototype.delete(value) -
从
该
WeakSet对象中删除value这个元素, 之后WeakSet.prototype.has(value)方法便会返回false. -
WeakSet.prototype.has(value) -
返回一个布尔值, 表示给定的值
value是否存在于这个WeakSet中.
示例
例1: 使用 WeakSet
var ws = new WeakSet();
var obj = {};
var foo = {};
ws.add(window);
ws.add(obj);
ws.has(window); // true
ws.has(foo); // false, 对象 foo 并没有被添加进 ws 中
ws.delete(window); // 从集合中删除 window 对象
ws.has(window); // false, window 对象已经被删除了
ws.clear(); // 清空整个 WeakSet 对象
规范
| 规范链接 | 规范状态 | 备注 |
|---|---|---|
| ECMAScript 2015 (6th Edition, ECMA-262) WeakSet |
Standard | 无 |
浏览器兼容性
We're converting our compatibility data into a machine-readable JSON format. This compatibility table still uses the old format, because we haven't yet converted the data it contains.
Find out how you can help!
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | (Yes) | 未实现 bug 792439 | 未实现 | 未实现 | 未实现 |
| Feature | Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|
| Basic support | 未实现 | 未实现 bug 792439 | 未实现 | 未实现 | 未实现 |
Chrome 备注
- 需在
chrome://flags 中开启“启用实验性 JavaScript” 才能使用该特性.