Here we focus on the differences between them and the corresponding sets and maps.
- WeakSet
- Cannot traverse, no forEach, no size
- Only objects can be added
- The garbage collector does not consider the WeakSet reference to the object at all.
- WeakMap
- Keys can only be objects
- The address where its key is stored does not affect garbage collection.
let obj ={
name: 'Tom',
age: 20
}
let map = new WeakMap();
obj = null; // 当obj设置为空之后,obj指向的这块内存地址就会被垃圾回收器回收
console.log(map);
The printing results are as follows. We find that there are no key values in the map.