WeakMap

Sumário

O objeto WeakMap é uma coleção de pares key/value na qual as chaves são fracamente referenciadas.
As chaves devem ser objetos, e os valores podem ser de tipos arbitrários.

Você pode descobrir mais sobre WeakMaps na seção WeakMap object in Keyed collections.

Sintaxe

new WeakMap([iterable])

Parâmetros

iterable
Iterable é um Array ou outro objeto iterável cujos elementos são pares key-value (Arrays de dois elementos). Cada par key-value será adicionados ao novo WeakMapnull é tratado como undefined.

Descrição

Por quê WeakMap?

Um programador JavaScript experiente vai notar que esta API pode ser implementada em JavaScript com dois arrays (um para chaves, um para valores) compartilhado pelos 4 métodos da API. Tal implementação teria duas principais incoveniências. A primeira é uma busca O(n) (n sendo o número de chaves no map). A segunda é o problema de memory leak. Com maps escritos manualmente, o array de chaves guardaria referências para objetos chave, prevenindo-os de serem coletados pelo Garbage Collector. Nos WeakMaps nativos, referências aos objetos chave são segurados de modo "fraco", o que significa que eles não previnem a coleção pelo GC no caso de não haver nenhuma outra referência ao objeto. 

Por conta das referências serem fracas, chaves de WeakMap não são enumeráveis (i.e. não existe um método que dá a você uma lista de chaves). Se existisse tal método, a lista dependeria no estado da coleção do GC, introduzindo não-determinismo. Se você quiser ter uma lista de chaves, deve usar um Map

Propriedades

WeakMap.length
O valor da propriedade length é 0.
WeakMap.prototype
Representa o prototype para o constructor WeakMap. Permite a adição de propriedades para todos os objetos WeakMap.

Instâncias WeakMap

Todas as instâncias WeakMap herdam de WeakMap.prototype.

Propriedades

WeakMap.prototype.constructor
Retorna a função construtora das instâncias, neste caso a própria WeakMap.

Métodos

WeakMap.prototype.clear()
Remove todos os pares chave/valor do objeto WeakMap
WeakMap.prototype.delete(key)
Remove qualquer valor associado à  keyWeakMap.prototype.has(key) e retorna false após.
WeakMap.prototype.get(key)
Retorna o valor associado a key, ou undefined se nenhum existir.
WeakMap.prototype.has(key)
Retorna um Boolean verificando se há algum valor associado a key no objeto WeakMap ou não.
WeakMap.prototype.set(key, value)
Configura um valor para key no objeto WeakMap. Retorna undefined.

Exemplos

Exemplo: Usando WeakMap

var wm1 = new WeakMap(),
    wm2 = new WeakMap(),
    wm3 = new WeakMap();
var o1 = {},
    o2 = function(){},
    o3 = window;

wm1.set(o1, 37);
wm1.set(o2, "azerty");
wm2.set(o1, o2); // um valor pode ser qualquer coisa, incluindo um objeto or uma função
wm2.set(o3, undefined);
wm2.set(wm1, wm2); // chaves e valores pode ser quaisquer objetos. Até mesmo WeakMaps! 

wm1.get(o2); // "azerty"
wm2.get(o2); // undefined, pois não existe valor para o2 em wm2 
wm2.get(o3); // undefined, pois este é o valor definido

wm1.has(o2); // true
wm2.has(o2); // false
wm2.has(o3); // true (mesmo se o valor armazenado for 'undefined')

wm3.set(o1, 37);
wm3.get(o1); // 37
wm3.clear();
wm3.get(o1); // undefined, pois wm3 foi 'limpado' e não há mais valor para o1.

wm1.has(o1);   // true
wm1.delete(o1);
wm1.has(o1);   // false

Especificações

Especificações Status Comentário
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'WeakMap' in that specification.
Padrão Definição inicial.
ECMAScript Latest Draft (ECMA-262)
The definition of 'WeakMap' in that specification.
Rascunho  

Compatibilidade com browsers


Update compatibility data on GitHub
DesktopMobileServer
ChromeEdgeFirefoxInternet ExplorerOperaSafariAndroid webviewChrome for AndroidFirefox for AndroidOpera for AndroidSafari on iOSSamsung InternetNode.js
WeakMapChrome Full support 36Edge Full support 12Firefox Full support 6IE Full support 11Opera Full support 23Safari Full support 8WebView Android Full support 37Chrome Android Full support 36Firefox Android Full support 6Opera Android Full support 24Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
Full support 0.12
Full support 0.10
Disabled
Disabled From version 0.10: this feature is behind the --harmony runtime flag.
clear
DeprecatedNon-standard
Chrome No support 36 — 43Edge No support NoFirefox No support 20 — 46IE Full support 11Opera No support 25 — 30Safari No support 8 — 9WebView Android No support 37 — 43Chrome Android No support 36 — 43Firefox Android No support 20 — 46Opera Android No support 25 — 30Safari iOS No support 8 — 9Samsung Internet Android Full support Yesnodejs Full support Yes
deleteChrome Full support 36Edge Full support 12Firefox Full support 6
Notes
Full support 6
Notes
Notes Prior to Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
IE Full support 11Opera Full support 23Safari Full support 8WebView Android Full support 37Chrome Android Full support 36Firefox Android Full support 6
Notes
Full support 6
Notes
Notes Prior to Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
Opera Android Full support 24Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
Full support 0.12
Full support 0.10
Disabled
Disabled From version 0.10: this feature is behind the --harmony runtime flag.
getChrome Full support 36Edge Full support 12Firefox Full support 6
Notes
Full support 6
Notes
Notes Prior to Firefox 38, this method threw a TypeError when the key parameter was not an object. However, the ES2015 specification specifies to return undefined instead. Furthermore, WeakMap.prototype.get accepted an optional second argument as a fallback value, which is not part of the standard. Both non-standard behaviors are removed in version 38 and higher.
IE Full support 11Opera Full support 23Safari Full support 8WebView Android Full support 37Chrome Android Full support 36Firefox Android Full support 6
Notes
Full support 6
Notes
Notes Prior to Firefox 38, this method threw a TypeError when the key parameter was not an object. However, the ES2015 specification specifies to return undefined instead. Furthermore, WeakMap.prototype.get accepted an optional second argument as a fallback value, which is not part of the standard. Both non-standard behaviors are removed in version 38 and higher.
Opera Android Full support 24Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
Full support 0.12
Full support 0.10
Disabled
Disabled From version 0.10: this feature is behind the --harmony runtime flag.
hasChrome Full support 36Edge Full support 12Firefox Full support 6
Notes
Full support 6
Notes
Notes Prior to Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
IE Full support 11Opera Full support 23Safari Full support 8WebView Android Full support 37Chrome Android Full support 36Firefox Android Full support 6
Notes
Full support 6
Notes
Notes Prior to Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
Opera Android Full support 24Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
Full support 0.12
Full support 0.10
Disabled
Disabled From version 0.10: this feature is behind the --harmony runtime flag.
prototypeChrome Full support 36Edge Full support YesFirefox Full support 6IE Full support 11Opera Full support 23Safari Full support 8WebView Android Full support 37Chrome Android Full support 36Firefox Android Full support 6Opera Android Full support 24Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
Full support 0.12
Full support 0.10
Disabled
Disabled From version 0.10: this feature is behind the --harmony runtime flag.
setChrome Full support 36Edge Full support 12Firefox Full support 6
Notes
Full support 6
Notes
Notes Prior to Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
IE Partial support 11
Notes
Partial support 11
Notes
Notes Returns 'undefined' instead of the 'Map' object.
Opera Full support 23Safari Full support 8WebView Android Full support 37Chrome Android Full support 36Firefox Android Full support 6
Notes
Full support 6
Notes
Notes Prior to Firefox 38, this method threw a TypeError when the key parameter was not an object. This has been fixed in version 38 and later to return false as per the ES2015 standard.
Opera Android Full support 24Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
Full support 0.12
Full support 0.10
Disabled
Disabled From version 0.10: this feature is behind the --harmony runtime flag.
new WeakMap(iterable)Chrome Full support 38Edge Full support 12Firefox Full support 36IE No support NoOpera Full support 25Safari Full support 9WebView Android Full support 38Chrome Android Full support 38Firefox Android Full support 36Opera Android Full support 25Safari iOS Full support 9Samsung Internet Android Full support Yesnodejs Full support 0.12
new WeakMap(null)Chrome Full support YesEdge Full support 12Firefox Full support 37IE Full support 11Opera Full support YesSafari Full support 8WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 37Opera Android ? Safari iOS Full support 8Samsung Internet Android Full support Yesnodejs Full support 0.12
Full support 0.12
Full support 0.10
Disabled
Disabled From version 0.10: this feature is behind the --harmony runtime flag.
WeakMap() without new throwsChrome Full support YesEdge Full support 12Firefox Full support 42IE Full support 11Opera Full support YesSafari Full support 9WebView Android Full support YesChrome Android Full support YesFirefox Android Full support 42Opera Android Full support YesSafari iOS Full support 9Samsung Internet Android Full support Yesnodejs Full support 0.12

Legend

Full support  
Full support
Partial support  
Partial support
No support  
No support
Compatibility unknown  
Compatibility unknown
Non-standard. Expect poor cross-browser support.
Non-standard. Expect poor cross-browser support.
Deprecated. Not for use in new websites.
Deprecated. Not for use in new websites.
See implementation notes.
See implementation notes.
User must explicitly enable this feature.
User must explicitly enable this feature.
 

Veja também