ECMAScript 6: what is WeakSet for?

后端 未结 7 703
北荒
北荒 2020-11-29 22:20

The WeakSet is supposed to store elements by weak reference. That is, if an object is not referenced by anything else, it should be cleaned from the WeakSet.

I have

相关标签:
7条回答
  • 2020-11-29 22:50

    Your console was probably incorrectly showing the contents due to the fact that the garbage collection did not take place yet. Therefore since the object wasn't garbage collected it would show the object still in weakset.

    If you really want to see if a weakset still has a reference to a certain object then use the WeakSet.prototype.has() method. This method, as the name implies returns a boolean indicating wether the object still exists in the weakset.

    Example:

    var weakset = new WeakSet(),
        numbers = [1, 2, 3];
    
    weakset.add(numbers);
    weakset.add({name: "Charlie"});
    
    console.log(weakset.has(numbers));
    
    numbers = undefined;
    
    console.log(weakset.has(numbers));

    0 讨论(0)
提交回复
热议问题