1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
  | 
---
title: WeakMap
slug: Web/JavaScript/Reference/Global_Objects/WeakMap
tags:
  - ECMAScript 2015
  - JavaScript
  - WeakMap
translation_of: Web/JavaScript/Reference/Global_Objects/WeakMap
original_slug: Web/JavaScript/Referencia/Objetos_globales/WeakMap
---
<div>{{JSRef}}</div>
<p>El objeto <strong><code>WeakMap</code></strong> es una colección de pares clave/valor en la que las claves son objetos y los valores son valores arbitrarios.</p>
<h2 id="Sintaxis">Sintaxis</h2>
<pre class="syntaxbox notranslate"><code>new WeakMap([iterable])
</code></pre>
<h3 id="Parámetros">Parámetros</h3>
<dl>
 <dt><code>iterable</code></dt>
 <dd>Iterable es un Array u otro objeto iterable cuyos elementos son pares clave-valor (Arrays de dos elementos). Cada par clave-valor será añadido al nuevo WeakMap. null es tratado como undefined.</dd>
</dl>
<h2 id="Descripción">Descripción</h2>
<p>Las claves de los WeakMaps solamente pueden ser del tipo<code> Object</code>. Los {{Glossary("Primitive", "Primitive data types")}} como claves no están permitidos (ej. un {{jsxref("Symbol")}} no pueden ser una clave de <code>WeakMap</code>).</p>
<h3 id="¿Por_qué_WeakMap">¿Por qué <em>Weak</em>Map?</h3>
<p>El programador de JavaScript experimentado se habrá dado cuenta que esta API podría ser implementada en JavaScript con dos arrays (uno para las claves, otro para los valores) compartidos por los cuatro métodos de la API. Dicha implementación habría tenido dos inconvenientes principales: El primero es una búsqueda O(n) (siendo n el número de claves en el mapa). El segundo es un problema de pérdida de memoria. Con mapas escritos manualmente, el array de las claves mantendría referencias a la objetos clave, impidiéndoles ser recolectados. En los WeakMap nativos, las referencias a los objetos clave son mantenidas "débilmente", lo que quiere decir que no impiden la recolección de basura en caso de que no haya otras referencias al objeto.</p>
<p>Dado que las referencias son débiles, <code>las claves de WeakMap</code> no son enumerables (ej: no existe un método que te devuelva la lista de las claves). Si existiera, la lista dependería de la recolección de basura, introduciendo indeterminismo. Si quieres una lista de las claves, se debe usar un  {{jsxref("Map")}} o mantenerla tu mismo.</p>
<h2 id="Propiedades">Propiedades</h2>
<dl>
 <dt><code>WeakMap.length</code></dt>
 <dd>El valor de la propiedad <code>length</code> es 0.</dd>
 <dt>{{jsxref("WeakMap.prototype")}}</dt>
 <dd>Representa el prototipo para el nuevo constructor<code> WeakMap</code>. Permite añadir propiedades a todos los objetos <code>WeakMap</code>.</dd>
</dl>
<h2 id="Instancias_de_WeakMap"><code>Instancias de WeakMap</code></h2>
<p>Todas las instancias de <code>WeakMap</code> heredan de {{jsxref("WeakMap.prototype")}}.</p>
<h3 id="Propiedades_2">Propiedades</h3>
<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/WeakMap/prototype','Properties')}}</p>
<h3 id="Métodos">Métodos</h3>
<p>{{page('en-US/Web/JavaScript/Reference/Global_Objects/WeakMap/prototype','Methods')}}</p>
<h2 id="Ejemplos">Ejemplos</h2>
<h3 id="Usando_WeakMap">Usando <code>WeakMap</code></h3>
<pre class="brush: js notranslate">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 valor puede ser cualquier cosa, incluidos objetos o funciones
wm2.set(o3, undefined);
wm2.set(wm1, wm2); // claves y valores pueden ser objetos cualesquiera. !Incluso WeakMaps!
wm1.get(o2); // "azerty"
wm2.get(o2); // undefined, porque no hay valor para o2 en wm2
wm2.get(o3); // undefined, porque es es el valor del conjunto
wm1.has(o2); // true
wm2.has(o2); // false
wm2.has(o3); // true (incluso si el valor es 'undefined')
wm3.set(o1, 37);
wm3.get(o1); // 37
wm1.has(o1);   // true
wm1.delete(o1);
wm1.has(o1);   // false
</pre>
<h3 id="Implementando_una_clase_tipo-WeakMap_con_un_método_.clear">Implementando una clase tipo-<code>WeakMap</code> con un método .clear()</h3>
<p>Con propósito expositivo, el siguiente ejemplo usa el nuevo costruct class  de ECMAScript 2015, que actualmente no ha sido implementado de forma amplia.</p>
<pre class="brush: js notranslate">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
  }
}
</pre>
<h2 id="Especificaciones">Especificaciones</h2>
<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Especificación</th>
   <th scope="col">Estado</th>
   <th scope="col">Comentario</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('ES2015', '#sec-weakmap-objects', 'WeakMap')}}</td>
   <td>{{Spec2('ES2015')}}</td>
   <td>Definición inicial.</td>
  </tr>
 </tbody>
</table>
<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2>
<p>{{CompatibilityTable}}</p>
<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Característica</th>
   <th>Chrome</th>
   <th>Firefox (SpiderMonkey)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Soporte básico</td>
   <td>36</td>
   <td>{{CompatGeckoDesktop("6.0")}}</td>
   <td>11</td>
   <td>{{ CompatOpera(23) }}</td>
   <td>7.1</td>
  </tr>
  <tr>
   <td><code>new WeakMap(iterable)</code></td>
   <td>38</td>
   <td>{{CompatGeckoDesktop("36")}}</td>
   <td>{{CompatNo}}</td>
   <td>{{ CompatOpera(25) }}</td>
   <td>{{CompatNo}}</td>
  </tr>
  <tr>
   <td><code>clear()</code></td>
   <td>36</td>
   <td>{{CompatGeckoDesktop("20.0")}}</td>
   <td>11</td>
   <td>{{ CompatOpera(23) }}</td>
   <td>7.1</td>
  </tr>
  <tr>
   <td>Constructor argument: <code>new WeakMap(null)</code></td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoDesktop("37")}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
  <tr>
   <td>Monkey-patched <code>set()</code> in Constructor</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoDesktop("37")}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
  <tr>
   <td><code>WeakMap()</code> without <code>new</code> throws</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoDesktop("42")}}</td>
   <td>11</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>
<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Característica</th>
   <th>Android</th>
   <th>Firefox Mobile (SpiderMonkey)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>Safari Mobile</th>
  </tr>
  <tr>
   <td>Soporte básico</td>
   <td>35</td>
   <td>{{CompatGeckoMobile("6.0")}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>iOS 8</td>
  </tr>
  <tr>
   <td><code>new WeakMap(iterable)</code></td>
   <td>38</td>
   <td>{{CompatGeckoMobile("36")}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
  </tr>
  <tr>
   <td><code>clear()</code></td>
   <td>35</td>
   <td>{{CompatGeckoMobile("20.0")}}</td>
   <td>{{CompatNo}}</td>
   <td>{{CompatNo}}</td>
   <td>iOS 8</td>
  </tr>
  <tr>
   <td>Constructor argument: <code>new WeakMap(null)</code></td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoMobile("37")}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
  <tr>
   <td>Monkey-patched <code>set()</code> in Constructor</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatGeckoMobile("37")}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
  </tr>
  <tr>
   <td><code>WeakMap()</code> without <code>new</code> throws</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatGeckoMobile("42")}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td></td>
   <td></td>
  </tr>
 </tbody>
</table>
</div>
<h2 id="sect1"></h2>
<h2 id="Ver_también">Ver también</h2>
<ul>
 <li><a class="link-https" href="https://bugzilla.mozilla.org/show_bug.cgi?id=547941">WeakMap bug en Mozilla</a></li>
 <li><a href="http://fitzgeraldnick.com/weblog/53/">Ocultando los detalles de implementación con los WeakMaps de ECMAScript </a>2015</li>
 <li>{{jsxref("Map")}}</li>
 <li>{{jsxref("Set")}}</li>
 <li>{{jsxref("WeakSet")}}</li>
</ul>
 
  |