js WeakMap All In One


js WeakMap All In One

A WeakMap is a collection of key/value pairs whose keys must be objects, with values of any arbitrary JavaScript type, and which does not create strong references to its keys.

WeakMap 是键/值对的集合,其键必须是对象,具有任意 JavaScript 类型的值,并且不会创建对其键的强引用。

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, 'azerty');

wm2.set(o1, o2); 
// a value can be anything, including an object or a function
wm2.set(o3, undefined);

wm2.set(wm1, wm2); 
// keys and values can be any objects. Even WeakMaps!

wm1.get(o2); // "azerty"
wm2.get(o2); // undefined, because there is no key for o2 on wm2
wm2.get(o3); // undefined, because that is the set value

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

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

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


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;
  }
}


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap

refs

https://www.cnblogs.com/xgqfrms/tag/WeakMap/


Flag Counter

?xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有??xgqfrms, 禁止转载 ???,侵权必究??!