• 首页
  • vue
  • TypeScript
  • JavaScript
  • scss
  • css3
  • html5
  • php
  • MySQL
  • redis
  • jQuery
  • new WeakSet()

    WeakSet对象允许你将弱保持对象存储在一个集合中。

    语法

     new WeakSet([iterable]);
    

    iterable:如果传入一个可迭代对象作为参数,则该对象的所有迭代值都会被自动添加进生成的WeakSet对象中。


    描述

    WeakSet对象是一些对象值的集合,并且其中的每个对象值都只能出现一次.

    它和Set对象的区别有两点:

    • WeakSet对象中只能存放对象引用,不能存放值,而Set对象都可以.


    • WeakSet对象中存储的对象值都是被弱引用的,如果没有其他的变量或属性引用这个对象值,则这个对象值会被当成垃圾回收掉。正因为这样,WeakSet对象是无法被枚举的,没有办法拿到它包含的所有元素.


    实例

    const ws = new WeakSet();
    const foo = {};
    const bar = {};
    
    ws.add(foo);
    ws.add(bar);
    
    ws.has(foo); // true
    ws.has(bar); // true
    
    ws.delete(foo); // removes foo from the set
    ws.has(foo); // false, foo has been removed
    ws.has(bar); // true, bar is retained
    

    Note that foo !== bar. While they are similar objects,they are not the same object. And so they are both added to the set.

    上篇:WeakSet

    下篇:WeakSet.prototype.add()