WeakSet
WeakSet
WeakSet
对象允许你将弱保持对象
存储在一个集合中。
语法
new WeakSet([iterable]
参数
iterable如果传入一个可迭代对象作为参数, 则该对象的所有迭代值都会被自动添加进生成的 WeakSet
对象中.
描述
WeakSet
对象是一些对象值的集合, 并且其中的每个对象值都只能出现一次.
它和 Set
对象的区别有两点:
WeakSet
对象中只能存放对象引用, 不能存放值, 而Set
对象都可以.
WeakSet
对象中存储的对象值都是被弱引用的, 如果没有其他的变量或属性引用这个对象值, 则这个对象值会被当成垃圾回收掉. 正因为这样,WeakSet
对象是无法被枚举的, 没有办法拿到它包含的所有元素.
属性
WeakSet.lengthlength
属性的值为 0.
WeakSet 实例
所有WeakSet
实例都继承自WeakSet.prototype
.
属性
WeakSet.prototype.constructor
返回构造函数即WeakSet
本身.
方法
WeakSet.prototype.add(value)
在该 WeakSet
对象中添加一个新元素value
.
示例
例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 has not been added to the set
ws.delete(window // removes window from the set
ws.has(window // false, window has been removed
规范
Specification | Status | Comment |
---|---|---|
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'WeakSet' in that specification. | Standard | Initial definition. |
ECMAScript Latest Draft (ECMA-262)The definition of 'WeakSet' in that specification. | Living Standard | |
浏览器兼容性
Feature | Chrome | Edge | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|---|
Basic support | 36 | 12 | 34 (34) | No support | 23 | 9 |
new WeakSet(iterable) | 38 | 12 | 34 (34) | No support | 25 | 9 |
Constructor argument: new WeakSet(null) | (Yes) | 12 | 37 (37) | No support | ? | 9 |
Obsolete clear() method removed | 43 | 12 | 46 (46) | No support | 30 | 9 |
Feature | Android | Edge | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | No support | (Yes) | 34.0 (34) | No support | No support | 9 |
new WeakMap(iterable) | No support | (Yes) | 34.0 (34) | No support | No support | 9 |
Constructor argument: new WeakSet(null) | ? | (Yes) | (Yes) | No support | ? | 9 |
Obsolete clear() method removed | No support | (Yes) | ? | No support | ? | 9 |