WeakMap and WeakSet in ES6

Here we focus on the differences between them and the corresponding sets and maps.

  • WeakSet
  1. Cannot traverse, no forEach, no size
  2. Only objects can be added
  3. The garbage collector does not consider the WeakSet reference to the object at all.
  • WeakMap
  1. Keys can only be objects
  2. 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.
Insert image description here

Guess you like

Origin blog.csdn.net/qq_42931285/article/details/132946302