- How does the
WeakMap
object work? - What's the difference between it and a
Object
(which is the most common in Javascript)? - What is the difference between
WeakMap
and Map ? - Which browsers can I use?
WeakMap
object work? Object
(which is the most common in Javascript)? WeakMap
and Map ? I recommend reading the question on Map
first. The type WeakMap
works exactly like Map
, with the following main differences:
The last one is in bold because it is the reason why WeakMap
exists. A "weak reference" in this context means that the use of a given object as a key in a WeakMap
does not count from the garbage collector's point of view. If there is no other reference to an object used as a key in a WeakMap
, the value corresponding to that key in WeakMap
is released to be collected by the garbage collector .
WeakMap
is an object of Javascript
that provides an object dictionary, that is, an object that stores data in the key / value format.
As a dictionary, it works based on a key, that is, for include / retrieve / delete operations is using a key to identify the object.
Here is an example of creating a dictionary and the basic operations:
var dic = new WeakMap()
//chaves
var chaveA = { chave: 'A' };
var chaveB = { chave: 'B' };
var chaveC = { chave: 'C' };
// adicionando objetos
dic.set(chaveA, 1);
dic.set(chaveB, "dois");
dic.set(chaveC, new Date(2018,06,13));
// verificando objetos
console.log("existe objeto 'A':" + dic.has(chaveA));
// recuperando
console.log("valor do objeto 'A':" + dic.get(chaveA));
console.log("valor do objeto 'B':" + dic.get(chaveB));
console.log("valor do objeto 'C':" + dic.get(chaveC));
// excluindo
dic.delete(chaveA);
console.log("existe objeto 'A':" + dic.has(chaveA));
Key differences:
get()
; set()
of WeakMap, it is necessary to use the =
operator; clear()
of WeakMap; Key differences:
forEach
, since WeakMap does not. string
, number
, etc), while WeakMap must be Object
. According to developer.mozila.org on 7/13/2018 the compatibility is:
Chrome Firefox Internet Explorer Opera Safari
36 6.0 (6.0) 11 Não suportado Não suportado