ES6 Set, WeakSet, Map and WeakMap

There are already some questions about maps and weak maps, for example: What is the difference between ES6 Map and WeakMap? but I would like to ask in what situation do I advocate the use of these data structures? Or what should I consider when I advocate for others?

Examples of data structures from: https://github.com/lukehoban/es6features

// Sets
var s = new Set();
s.add("hello").add("goodbye").add("hello");
s.size === 2;
s.has("hello") === true;

// Maps
var m = new Map();
m.set("hello", 42);
m.set(s, 34);
m.get(s) == 34;

// Weak Maps
var wm = new WeakMap();
wm.set(s, { extra: 42 });
wm.size === undefined

// Weak Sets
var ws = new WeakSet();
ws.add({ data: 42 });
// Because the added object has no other references, it will not be held in the set

Bonus Which of the above data structures will produce the same / similar result:let hash = object.create(null); hash[index] = something;

+4
source share
1 answer

This is described in §23.3 of the specification:

, "/" WeakMap, , WeakMap, / WeakMap.

, , , - .

, a Map , , - , .

MDN :

WeakMap . , , WeakMap .

WeakSet .

... ?

, , /, , .

, , , , :

let Thing = (() => {
    var privateData = new WeakMap();

    class Thing {
        constructor() {
            privateData[this] = {
                foo: "some value"
            };
        }

        doSomething() {
            console.log(privateData[this].foo);
        }
    }

    return Thing;
})();

privateData. . WeakMap, , Thing . WeakMap , , Thing , WeakMap ; , , .

/ : let hash = Object.create(null); hash[index] = something;

Map, index ( ) ​​ ( , ).

+8

Source: https://habr.com/ru/post/1608432/


All Articles