WeakMap

L'oggetto WeakMap è una collezione di coppie chiave/valore in cui le chiavi hanno una referenza debole. Le chiavi devono essere oggetti e il tipo dei valori è arbitrario.

Puoi leggere altri dettagli sulle WeakMap nella sezione WeakMap object in Keyed collections.

Sintassi

new WeakMap([iterable])

Parametri

iterable
Iterable è un array o altro oggetto iterabile i cui elementi sono coppie chiave/valore (array di due elementi). Ogni coppia è aggiunta ad una nuova WeakMap. Null è trattato come undefined.

Descrizione

Keys of WeakMaps are of the type Object only. Primitive data types as keys are not allowed (e.g. a Symbol can't be a WeakMap key).

Perché WeakMap?

Una API per una mappa può essere implementata in Javascript con due array (uno per le chiavi, uno per i valori) condivisi dai quattro metodi dell'API. Settare gli elementi di questa mappa vorrebbe dire effettuare un push di una coppia chiave/valore in coda a ciascuno dei due array simultaneamente, in modo che gli indici delle chiavi e dei valori corrispondano nei due array. Trovare un valore dalla mappa vorrebbe dire iterare su tutte le chiavi per trovare quella desiderata e poi usare l'indice di questo match per recuperare il valore corrispondente dall'array dei valori.

Una tale implementazione avrebbe due principali aspetti negatiivi. Il primo è che il tempo di settaggio o ricerca sarebbe O(n) dato che entrambe le operazioni dovrebbero iterare sulle liste delle chiavi per trovare il valore corretto. Il secondo è un memory leak perché con gli array i riferimenti ad ogni chiave e valore sono mantenuti indefinitivamente e non possono essere soggetti a garbage collection.

Al contrario, WeakMaps mantengono referenze "deboli" ad oggetti che fungono da chiavi e che possono essere garbage collected quando questi oggetti non hanno altri riferimenti. Questo permette anche la garbage collection dei valori della WeakMap. Le WeakMap possono essere particolarmente utili quando si mappano chiavi ad informazioni sulle chiavi che sono importanti solo se la chiave non è stata garbage collected.

Dato che i riferimenti sono deboli, le chiavi WeakMap non sono enumerabili (non esiste un metodo che fornisce una lista delle chiavi). Se le chiavi fossero enumerabili, la lista dipenderebbe dallo stato della garbage collection e sarebbe quindi non-deterministica. Se si vuole ottenere una lista delle chiavi, è consigliato usare una Map.

Proprietà

WeakMap.length
Il valore della proprietà length è 0.
WeakMap.prototype
Rappresenta il prototipo per il costruttore WeakMap. Consente l'aggiunta di proprietà a tutti gli oggetti WeakMap.

Istanze WeakMap

Tutte le istanze WeakMap ereditano da WeakMap.prototype.

Properties

WeakMap.prototype.constructor
Returns the function that created an instance's prototype. This is the WeakMap function by default.

Methods

WeakMap.prototype.delete(key)
Removes any value associated to the key. WeakMap.prototype.has(key) will return false afterwards.
WeakMap.prototype.get(key)
Returns the value associated to the key, or undefined if there is none.
WeakMap.prototype.has(key)
Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not.
WeakMap.prototype.set(key, value)
Sets the value for the key in the WeakMap object. Returns the WeakMap object.
WeakMap.prototype.clear()
Removes all key/value pairs from the WeakMap object. Note that it is possible to implement a WeakMap-like object that has a .clear() method by encapsulating a WeakMap object that hasn't it (see example on page WeakMap)

Esempi

Usare 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); // un valore può essere anche un oggetto o funzione
wm2.set(o3, undefined);
wm2.set(wm1, wm2); // chiavi e valori possono essere un oggetto qualunque, incluso una WeakMap!

wm1.get(o2); // "azerty"
wm2.get(o2); // undefined, perché non c'è chiave per o2 in wm2
wm2.get(o3); // undefined, perché questo è il valore settato

wm1.has(o2); // true
wm2.has(o2); // false
wm2.has(o3); // true (anche se il valore è 'undefined')

wm3.set(o1, 37);
wm3.get(o1); // 37

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

Implementare una classe WeakMap-like con un metodo .clear()

class ClearableWeakMap {
  constructor(init) {
    this._wm = new WeakMap(init)
  }
  clear() {
    this._wm = new WeakMap()
  }
  delete(k) {
    return this._wm.delete(k)
  }
  get(k) {
    return this._wm.get(k)
  }
  has(k) {
    return this._wm.has(k)
  }
  set(k, v) {
    this._wm.set(k, v)
    return this
  }
}

Specifiche

Specifica Stato Commento
ECMAScript Latest Draft (ECMA-262)
The definition of 'WeakMap' in that specification.
Draft
ECMAScript 2015 (6th Edition, ECMA-262)
The definition of 'WeakMap' in that specification.
Standard Definizione iniziale

Compatibilità browser

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 3.0nodejs 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 No support 3.0 — 4.0nodejs 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 3.0nodejs 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 3.0nodejs 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 3.0nodejs 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 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 3.0nodejs 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 3.0nodejs 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 3.0nodejs Full support 0.12
new WeakMap(null)Chrome Full support 36Edge Full support 12Firefox Full support 37IE Full support 11Opera Full support 23Safari Full support 8WebView Android Full support 37Chrome Android Full support 36Firefox Android Full support 37Opera Android Full support 24Safari iOS Full support 8Samsung Internet Android Full support 3.0nodejs 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 36Edge Full support 12Firefox Full support 42IE Full support 11Opera Full support 23Safari Full support 9WebView Android Full support 37Chrome Android Full support 36Firefox Android Full support 42Opera Android Full support 24Safari iOS Full support 9Samsung Internet Android Full support 3.0nodejs Full support 0.12

Legend

Full support  
Full support
Partial support  
Partial support
No support  
No support
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.

Vedi anche