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

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.

主站蜘蛛池模板: 龙井市| 丰都县| 杂多县| 常德市| 沙洋县| 黄梅县| 通化县| 延庆县| 神农架林区| 内江市| 漳浦县| 崇文区| 栾川县| 牙克石市| 巴青县| 高安市| 隆尧县| 南阳市| 汨罗市| 临泽县| 南和县| 东台市| 四川省| 兴文县| 安岳县| 离岛区| 通化县| 上蔡县| 蓝山县| 镇康县| 贡嘎县| 玉门市| 日喀则市| 洛扎县| 连江县| 赣州市| 呼玛县| 台湾省| 鹤山市| 浏阳市| 乌兰察布市|