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

A comprehensive summary of frequently used statements in MySQL (must read)

The knowledge points summarized below are all fre...

A Different Kind of "Cancel" Button

The “Cancel” button is not part of the necessary ...

Detailed explanation of vue-router 4 usage examples

Table of contents 1. Install and create an instan...

In-depth explanation of environment variables and configuration files in CentOS

Preface The CentOS environment variable configura...

How to maintain a long connection when using nginx reverse proxy

· 【Scene description】 After HTTP1.1, the HTTP pro...

Native JS to implement login box email prompt

This article shares a native JS implementation of...

This article will help you understand the life cycle in Vue

Table of contents 1. beforeCreate & created 2...

Detailed explanation of using Vue.prototype in Vue

Table of contents 1. Basic Example 2. Set the sco...

MySQL Series 7 MySQL Storage Engine

1. MyISAM storage engine shortcoming: No support ...

Detailed explanation of loop usage in javascript examples

I was bored and sorted out some simple exercises ...

Linux file system operation implementation

This reading note mainly records the operations r...

How does MySQL ensure master-slave consistency?

Table of contents The basic principle of MySQL ma...