[英]What's the difference between ES6 Set and WeakSet?
ECMAScript 6 has these very similar collections: Set
and WeakSet
. ECMAScript 6 有这些非常相似的集合:
Set
和WeakSet
。 What is the difference between them?它们之间有什么区别?
The main difference is that references to objects in Set are strong while references to objects in WeakSet are weak. 主要区别在于对Set中对象的引用很强,而对WeakSet中对象的引用很弱。 This means that an object in WeakSet can be garbage collected if there is no other reference to it .
这意味着如果没有其他引用,WeakSet中的对象可以被垃圾收集 。
Other differences (or rather side-effects) are: 其他差异(或相反的副作用)是:
Weaksets are javascript objects which holds a collection of objects. 弱集是javascript对象,它包含一组对象。 Due to the nature of a set only one object reference of the same object may occur within the set.
由于集合的性质,集合中只能出现一个对象引用相同的对象。 A Weakset differs from a normal set in the following ways:
Weakset在以下方面与普通集不同:
int
, boolean
, string
) are allowed. int
, boolean
, string
)。 WeakSet
, the object can be be garbage collected (ie the JS engine will free the memory which object the reference was pointing to). WeakSet
之外没有其他对象的WeakSet
,对象可以被垃圾收集(即JS引擎将释放引用所指向的对象的内存)。 let myWeakSet = new WeakSet(); let obj = {}; myWeakSet.add(obj); console.log(myWeakSet.has(obj)); // break the last reference to the object we created earlier obj = 5; // false because no other references to the object which the weakset points to // because weakset was the only object holding a reference it released it and got garbage collected console.log(myWeakSet.has(obj));
Set:- A Set is a collection of values, where each value may occur only once. 设置: - Set是值的集合,其中每个值只能出现一次。 And main method are add, delete, has, clear and size.
主要方法有add,delete,has,clear和size。
WeakSet:- WeakSet objects allows you to store collection of unique key.“ WeakSet ” keys cannot be primitive types. WeakSet: - WeakSet对象允许您存储唯一键的集合。“ WeakSet ”键不能是原始类型。 Nor they can be created by an array or another set.
它们也不能由数组或其他集创建。 Values of WeakSet must be object reference.
WeakSet的值必须是对象引用。
这是用例的解释,有助于更好地理解这个概念
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.