[Translation] Set Type in ECMAScript 6, Part 3: WeakMap

Source: Internet
Author: User

Original article: http://www.nczonline.net/blog/2012/11/06/ecmascript-6-collections-part-3-weakmaps/

WeakMapSimilar to the conventionalMapThey map a value to a unique key, and then they can be used to obtain the corresponding value.WeakMapAndMapThe 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 makesWeakMapIt has become very valuable.

OneWeakMapThe 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,WeakMapThe key-Value Pair referenced in the object will also be deleted. UseWeakMapThe 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. useWeakMapJQuery can automatically release the memory occupied by some DOM elements after they are deleted from the document.

In ECMAScript 6WeakMapType is an unordered list of key-value pairs. The key must be a non-null object. The value can be of any type.WeakMapAndMapSame,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 thenWeakMapThe 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(elementInstead of passing in the reference of the DOM element. You cannot usenullComeWeakMapObject 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 (becauseelementThe value of is alreadynullWe 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.

WeakMapAnother 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.WeakMapHowever, in Chrome, you must manually enable the ECMAScript 6 feature:chrome://flagsCheck "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

CurrentlyWeakMapThere is a specific usage situation, that is, when the value is mapped to some objects that may be deleted in the future.WeakMapThis "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,WeakMapAfter the standard is fully implemented and widely used, more can be used.WeakMapSo in the short term, do not use it unexpectedly.WeakMapAnd worried.

In most casesMapIt should be your most appropriate choice.WeakMapThere 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 functionsWeakMapIs a good choice.

Reference
  1. WeakMapsStrawman (ECMA)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.