WeakMap objects are collections of key/value pairs where the keys are objects and values may be arbitrary ECMAScript language values. A WeakMap may be queried to see if it contains a key/value pair with a specific key, but no mechanism is provided for enumerating the objects it holds as keys. If an object that is being used as the key of a WeakMap key/value pair is only reachable by following a chain of references that start within that WeakMap, then that key/value pair is inaccessible and is automatically removed from the WeakMap. WeakMap implementations must detect and remove such key/value pairs and any associated resources.
class ElementData extends WeakMap {
constructor() {
// ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from deriv
}
}
Some use cases that would otherwise cause a memory leak and are enabled by WeakMaps include:
Keeping private data about a specific object and only giving access to it to people with a reference to the Map. A more ad-hoc approach is coming with the private-symbols proposal but that’s a long time from now.
Keeping data about library objects without changing them or incurring overhead.
Keeping data about a small set of objects where many objects of the type exists to not incur problems with hidden classes JS engines use for objects of the same type.
Keeping data about host objects like DOM nodes in the browser.
Adding a capability to an object from the outside (like the event emitter example in the other answer).