js-mythbusters icon indicating copy to clipboard operation
js-mythbusters copied to clipboard

Add WeakMaps section

Open Kikobeats opened this issue 7 years ago • 0 comments

Reading about Proxies at https://hacks.mozilla.org/2015/07/es6-in-depth-proxies-and-reflect/

I found a very nice WeakMaps usage example:

Proxies ♥ WeakMaps. In our readOnlyView example, we create a new proxy every time an object is accessed. It could save a lot of memory to cache every proxy we create in a WeakMap, so that however many times an object is passed to readOnlyView, only a single proxy is created for it.

  throw new Error("can't modify read-only view");
}

var handler = {
  // Override all five mutating methods.
  set: NOPE,
  defineProperty: NOPE,
  deleteProperty: NOPE,
  preventExtensions: NOPE,
  setPrototypeOf: NOPE
};

function readOnlyView(target) {
  return new Proxy(target, handler);
}

This is one of the motivating use cases for WeakMap.

Because WeakMaps is confused with Maps, could be interesting add a section about when to use WeakMaps

Kikobeats avatar Dec 24 '17 12:12 Kikobeats