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

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.

主站蜘蛛池模板: 贡山| 新巴尔虎左旗| 池州市| 福贡县| 禹州市| 惠安县| 沁源县| 三江| 原阳县| 富锦市| 金昌市| 清远市| 杂多县| 茌平县| 塔城市| 华安县| 鸡泽县| 无为县| 清新县| 湛江市| 酒泉市| 北碚区| 台东县| 泗阳县| 濉溪县| 恩平市| 三穗县| 宜兰县| 托里县| 横山县| 新闻| 霍林郭勒市| 苍梧县| 黑水县| 桓仁| 芦山县| 虹口区| 眉山市| 余姚市| 丹凤县| 安阳市|