Detailed explanation of using JavaScript WeakMap

Detailed explanation of using JavaScript WeakMap

A WeakMap object is a collection of key/value pairs where the keys are weak references. The keys must be objects, but the values ​​can be anything.

grammar

new WeakMap([iterable])

parameter

iterable
Iterable is an array (two-element array) or other iterable object whose elements are key-value pairs. Each key-value pair will be added to the new WeakMap. null is treated as undefined.

describe

The key of WeakMap can only be of Object type. Primitive data types cannot be used as keys (such as Symbol).

Why WeakMap?

In JavaScript, the map API can be implemented by having its four API methods share two arrays (one for keys and one for values). Setting a value to such a map appends both the key and the value to the end of both arrays. This makes the key and value indices correspond in the two arrays. When getting a value from the map, you need to traverse all the keys and then use the index to retrieve the corresponding value from the array of stored values.

However, such an implementation has two major disadvantages. First, the time complexity of both assignment and search operations is O(n) (n is the number of key-value pairs), because both operations require traversing the entire array for matching. Another disadvantage is that it may cause memory leaks because the array will always have a reference to each key and value. Such references prevent the garbage collection algorithm from reclaiming them, even if no other references exist.

In contrast, the native WeakMap holds a "weak reference" to each key object, which means that garbage collection can be performed correctly when no other references exist. The structure of the native WeakMap is special and effective, and the key used for mapping is valid only when it has not been recycled.

Because of this weak reference, the keys of WeakMap are not enumerable (there is no method to give all the keys). If key is enumerable, its list will be subject to garbage collection, resulting in undefined results. Therefore, if you want a list of key values ​​of this type of object, you should use a Map.

Basically, if you want to add data to an object and don't want to interfere with the garbage collection mechanism, you can use WeakMap.

property

  • WeakMap.length

The value of the length property is 0.

  • WeakMap.prototype

Prototype for the WeakMap constructor. Allows adding attributes to all WeakMap objects.

WeakMap Instance

All WeakMap instances inherit from WeakMap.prototype.

property

WeakMap.prototype.constructor
Returns the prototype function for creating WeakMap instances. The WeakMap function is the default.

method

  • WeakMap.prototype.delete(key)

Remove the object associated with key. After execution, WeakMap.prototype.has(key) returns false.

  • WeakMap.prototype.get(key)

Returns the object associated with key, or undefined (when there is no object associated with key).

  • WeakMap.prototype.has(key)

Returns a Boolean value based on whether the key is associated with the object.

  • WeakMap.prototype.set(key, value)

Set a set of key-associated objects in a WeakMap and return this WeakMap object.

Example

Using WeakMap

const wm1 = new WeakMap(),
   wm2 = new WeakMap(),
   wm3 = new WeakMap();
const o1 = {},
   o2 = function(){},
   o3 = window;

wm1.set(o1, 37);
wm1.set(o2, "azerty");
wm2.set(o1, o2); // value can be anything, including an object or a function wm2.set(o3, undefined);
wm2.set(wm1, wm2); // The key and value can be any object, even another WeakMap object wm1.get(o2); // "azerty"
wm2.get(o2); // undefined, there is no key o2 in wm2 wm2.get(o3); // undefined, the value is undefined

wm1.has(o2); // true
wm2.has(o2); // false
wm2.has(o3); // true (even if the value is undefined)

wm3.set(o1, 37);
wm3.get(o1); // 37

wm1.has(o1); // true
wm1.delete(o1);
wm1.has(o1); // false

Implement a WeakMap class with a .clear() method

class ClearableWeakMap {
 constructor(init) {
  this._wm = new WeakMap(init)
 }
 clear() {
  this._wm = new WeakMap()
 }
 delete(k) {
  return this._wm.delete(k)
 }
 get(k) {
  return this._wm.get(k)
 }
 has(k) {
  return this._wm.has(k)
 }
 set(k, v) {
  this._wm.set(k, v)
  return this
 }
}

specification

Specification Status Comment
ECMAScript 2015 (6th Edition, ECMA-262)
WeakMap
Standard Initial definition.
ECMAScript (ECMA-262)
WeakMap
Living Standard

The above is the detailed content of the detailed explanation of the use of JavaScript WeakMap. For more information about JavaScript WeakMap, please pay attention to other related articles on 123WORDPRESS.COM!

You may also be interested in:
  • Analysis of the differences between Object, map, and weakmap in JavaScript
  • Detailed explanation of the use of Map and WeakMap types in JavaScript

<<:  Install mysql5.7.17 using RPM under Linux

>>:  Detailed explanation of how to configure multi-threaded master-slave replication from MySQL 5.7 slave nodes

Recommend

How to write DROP TABLE in different databases

How to write DROP TABLE in different databases 1....

JavaScript implements constellation query function with detailed code

Table of contents 1. Title 2. Code 3. Results IV....

CentOS7 uses yum to install mysql 8.0.12

This article shares the detailed steps of install...

Usage of if judgment in HTML

In the process of Django web development, when wr...

Example analysis of mysql variable usage [system variables, user variables]

This article uses examples to illustrate the usag...

A brief discussion on two current limiting methods in Nginx

The load is generally estimated during system des...

Proxy realizes the principle of two-way binding of Vue3 data

Table of contents 1. Advantages of proxy vs. Obje...

How to use lazy loading in react to reduce the first screen loading time

Table of contents use Install How to use it in ro...

Detailed process of using nginx to build a webdav file server in Ubuntu

Install nginx Note that you must install nginx-fu...

Learn v-model and its modifiers in one article

Table of contents Preface Modifiers of v-model: l...

HTML tag dl dt dd usage instructions

Basic structure: Copy code The code is as follows:...

Application examples of WeChat applet virtual list

Table of contents Preface What is a virtual list?...

Let's talk in detail about the props attributes of components in Vue

Table of contents Question 1: How are props used ...