Original article: http://www.nczonline.net/blog/2012/11/06/ecmascript-6-collections-part-3-weakmaps/
WeakMap
Similar to the conventionalMap
They map a value to a unique key, and then they can be used to obtain the corresponding value.WeakMap
AndMap
The difference is that its key can only be the object value, not the original value. Although this restriction looks strange, it is exactly this that makesWeakMap
It has become very valuable.
OneWeakMap
The object key only holds the weak reference of the referenced object. The weak reference feature is that it cannot prevent the garbage collector from recycling the referenced object. When the object is destroyed by the garbage collector,WeakMap
The key-Value Pair referenced in the object will also be deleted. UseWeakMap
The most typical example is to create an object associated with a specific DOM element. for example, jQuery maintains some object caches in the program. Each cache references a DOM element. useWeakMap
JQuery can automatically release the memory occupied by some DOM elements after they are deleted from the document.
In ECMAScript 6WeakMap
Type is an unordered list of key-value pairs. The key must be a non-null object. The value can be of any type.WeakMap
AndMap
Same,set()
Andget()
Used to add data and obtain data respectively:
Var map = new WeakMap (),
Element = document. querySelector (". element ");
Map. set (element, "Original ");
// The following code can be used:
Var value = map. get (element );
Console. log (value); // "Original" // Delete the reference element. parentNode. removeChild (element) below );
Element = null;
// Note: The following statement will actually report an error (value is not a non-null object), because the key must be a non-null object. The author just wants to explain it. See the following.
Value = map. get (element );
Console. log (value); // undefined
In this example, a key-value pair is stored. The key is a DOM element and a corresponding string value is stored. Then, the DOM element is passed in.get()
Method to obtain the stored string value. If this DOM element is deleted from the document, the variable pointing to it is also assignednull
, And thenWeakMap
The key-value pair in the object will be automatically deleted. If you read the key-value pair again, it will fail.
This example is a bit misleading, because in the second callmap.get(element)
In factnull
(element
Instead of passing in the reference of the DOM element. You cannot usenull
ComeWeakMap
Object keys (WeakMap keys can only be objects, and null is not objects). Such code will throw an exception and will not be executed on the console. log statement. the above code is written for explanation only. the key-Value Pair does not exist. however, unfortunately, we have no way to check whether this key-value pair is actually deleted (becauseelement
The value of is alreadynull
We cannot get the reference pointing to that DOM element. If we can really get the reference of that DOM object and pass it to the get method, we should return undefined ).
Note: Due to the limited level of Chinese language, I cannot clearly express the above paragraph. so I have made a few pictures with my poor skills. I hope that my understanding is correct, and I hope that you can understand it.
var map = new WeakMap(),
element = document.querySelector(".element");
The map and element variables each reference an object.
map.set(element, "Original");
Map adds a key-value pair. This key and the variable element point to a DOM object at the same time, but one is a strong reference and the other is a weak reference.
element.parentNode.removeChild(element);
element = null;
All strong references are automatically disconnected, and the remaining weak references are also automatically disconnected. Isolated DOM elements are recycled, and corresponding key-value pairs in the WeakMap object are automatically cleared. if it is a regular Map, because it is not a weak reference, the DOM object will not be recycled, it still exists, and can still be accessed through the get () method.
WeakMap
Another objecthas()
Method to determine whether an object reference is used as its own key.delete()
To delete a key-value pair.
var map = new WeakMap(),
element = document.querySelector(".element");
map.set(element, "Original");
console.log(map.has(element)); // trueconsole.log(map.get(element)); // "Original"map.delete(element);
console.log(map.has(element)); // falseconsole.log(map.get(element)); // undefined
Usedelete()
Method to delete a key and then executehas()
Will returnfalse
, Executeget()
Method returnsundefined
.
Browser support
Both Firefox and Chrome have been implemented.WeakMap
However, in Chrome, you must manually enable the ECMAScript 6 feature:chrome://flags
Check "enable experimental JavaScript". The current browser implementation fully complies with the current strawman [1] specification (while the latest draft of ECMAScript 6 adds a newWeakMap.prototype.clear()
Methods, these two browsers have not yet been implemented ).
Usage and restrictions
CurrentlyWeakMap
There is a specific usage situation, that is, when the value is mapped to some objects that may be deleted in the future.WeakMap
This "ability to release memory occupied by some useless objects" is useful for JavaScript libraries that encapsulate DOM elements into custom objects (such as jQuery and YUI). in the future,WeakMap
After the standard is fully implemented and widely used, more can be used.WeakMap
So in the short term, do not use it unexpectedly.WeakMap
And worried.
In most casesMap
It should be your most appropriate choice.WeakMap
There are many restrictions, such as not enumerating key-value pairs (for of
), You cannot know how many key-value pairs they contain (size
). If you need to do this, use the regularMap
. If you only need to use some objects as keys and do not need other functionsWeakMap
Is a good choice.
Reference
- WeakMapsStrawman (ECMA)