[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ru/docs/Web/JavaScript/Reference/Global_Objects/WeakMap [Back]  [Original]

WeakMap - JavaScript | MDN

This page was translated from English by the community. Learn more and join the MDN Web Docs community.

View in English Always switch to English

WeakMap

Baseline Widely available *

This feature is well established and works across many devices and browser versions. Its been available across browsers since 2015 ..

* Some parts of this feature may have varying levels of support.

WeakMap -. , .

In this article

WeakMap . , . .

WeakMap?

JavaScript , map API JavaScript c ( , ) API . map . . map , , .

. O(n) ( n map), . . , , -, . WeakMap, - , , , .

WeakMaps "weak" () , , -. WeakMaps , , (Garbage collector).

- , , WeakMap ( , ). , . , .

WeakMap()

WeakMap.

WeakMap.prototype WeakMap.

WeakMap.prototype.constructor

-, . WeakMap WeakMap.

WeakMap.prototype[@@toStringTag]

@@toStringTag "WeakMap". Object.prototype.toString().

WeakMap.prototype.delete()

, key. WeakMap.prototype.has(key) false.

WeakMap.prototype.get()

, key undefined .

WeakMap.prototype.has()

, key WeakMap .

WeakMap.prototype.set()

value key WeakMap. WeakMap.

WeakMap

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

wm1.set(o1, 37);
wm1.set(o2, "");
wm2.set(o1, o2); //     ,    
wm2.set(o2, undefined);
wm2.set(wm1, wm2); //         WeakMap (!)

wm1.get(o2); // ""
wm2.get(o2); // undefined,      
wm2.get(o3); // undefined,    wm2   o3

wm1.has(o2); // true
wm2.has(o2); // true (     'undefined')
wm2.has(o3); // false

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

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

: WeakMap- .clear()

js
class ClearableWeakMap {
  #wm;
  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
ECMAScript 2027 LanguageSpecification
# sec-weakmap-objects


Web Proxy Viewer  |  New URL  |  Original Page