Javascript WeakMap Type

Introduction

The Javascript WeakMap is a collection of key/value pairs.

Its keys are weakly referenced.

The keys must be objects and the values can be arbitrary values.

WeakMap hold weak references to key objects, they do not prevent garbage collection.

Using WeakMap

let window = function() {};

const wm1 = new WeakMap(),//w  w w.j  a  va2 s  .c o  m
      wm2 = new WeakMap(),
      wm3 = new WeakMap();
const o1 = {},
      o2 = function() {},
      o3 = window;

wm1.set(o1, 37);
wm1.set(o2, 'ASDF');
wm2.set(o1, o2);
wm2.set(o3, undefined);
wm2.set(wm1, wm2);

console.log(wm1);
console.log(wm2);

let a = wm1.get(o2);
a = wm2.get(o2);
console.log(a);
a = wm2.get(o3);
console.log(a);

let b = wm1.has(o2); 
console.log(b);
b = wm2.has(o2); 
console.log(b);
b = wm2.has(o3); 
console.log(b);

wm3.set(o1, 37);
a = wm3.get(o1); 
console.log(a);

b = wm1.has(o1); 
console.log(b);

wm1.delete(o1);
b = wm1.has(o1);
console.log(b);



PreviousNext

Related