官术网_书友最值得收藏!

Understanding WeakSets

WeakSet is very similar to WeakMap; the values that a WeakSet can hold are only objects and cannot be primitives just like in the case of a WeakMap. The WeakSets are also not enumerable, so you do not have direct access to the values available inside the set.

Let's create a small example and understand the difference between a Set and a WeakSet: 

var set = new Set();
var wset = new WeakSet();

(function() {

var a = {a: 1};
var b = {b: 2};
var c = {c: 3};
var d = {d: 4};

set.add(1).add(2).add(3).add(4);
wset.add(a).add(b).add(b).add(d);

})();

console.dir(set);
console.dir(wset);

One important thing to note is that WeakSet does not accept primitives and can only accept objects similar to the WeakMap keys.

The output of the preceding code is as follows, which is what was expected from the WeakSet. WeakSet does not retain elements beyond the lifespan of the variables that were holding them:

As expected, the WeakSet is empty once the IIFE is terminated.

主站蜘蛛池模板: 漾濞| 肥东县| 宁波市| 鄂尔多斯市| 宁晋县| 海安县| 霞浦县| 诏安县| 邳州市| 东光县| 西青区| 木兰县| 临高县| 兴山县| 阿鲁科尔沁旗| 临安市| 青铜峡市| 彝良县| 合肥市| 盐边县| 新安县| 呼伦贝尔市| 高雄县| 阳东县| 金寨县| 岳普湖县| 湄潭县| 武宣县| 禄劝| 锡林郭勒盟| 盐城市| 顺昌县| 习水县| 察隅县| 科技| 瑞昌市| 南丹县| 黄陵县| 万全县| 庆安县| 福建省|