javascript中的WeakMap和WeakSet

Posted 低代码布道师

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript中的WeakMap和WeakSet相关的知识,希望对你有一定的参考价值。

WeakMap的key不能是基本类型

let weakMap = new WeakMap();

let obj = ;

weakMap.set(obj, "ok"); // works fine (object key)

// can't use a string as the key
weakMap.set("test", "Whoops"); // Error, because "test" is not an object

如果key指向了null,则key会被自动回收

let john =  name: "John" ;

let weakMap = new WeakMap();
weakMap.set(john, "...");

john = null; // overwrite the reference

// john is removed from memory!

WeekMap只有如下的方法

  • weakMap.get(key)
  • weakMap.set(key, value)
  • weakMap.delete(key)
  • weakMap.has(key)

什么时候使用这个数据结构,如果key失去了引用,那么就自动回收它,比如用户和用户的访问量,如果用户离开了,那么它的访问量也就没有存在的价值了,此时可以使用这个数据结构进行存储

let visitsCountMap = new WeakMap(); // weakmap: user => visits count

// increase the visits count
function countUser(user) 
  let count = visitsCountMap.get(user) || 0;
  visitsCountMap.set(user, count + 1);

另外一种用途就是缓存

let cache = new WeakMap();

// calculate and remember the result
function process(obj) 
  if (!cache.has(obj)) 
    let result = /* calculate the result for */ obj;

    cache.set(obj, result);
  

  return cache.get(obj);


// 📁 main.js
let obj = /* some object */;

let result1 = process(obj);
let result2 = process(obj);

// ...later, when the object is not needed any more:
obj = null;

// Can't get cache.size, as it's a WeakMap,
// but it's 0 or soon be 0
// When obj gets garbage collected, cached data will be removed as well

WeakSet可以用来记录哪些人访问了网站

let visitedSet = new WeakSet();

let john =  name: "John" ;
let pete =  name: "Pete" ;
let mary =  name: "Mary" ;

visitedSet.add(john); // John visited us
visitedSet.add(pete); // Then Pete
visitedSet.add(john); // John again

// visitedSet has 2 users now

// check if John visited?
alert(visitedSet.has(john)); // true

// check if Mary visited?
alert(visitedSet.has(mary)); // false

john = null;

// visitedSet will be cleaned automatically

以上是关于javascript中的WeakMap和WeakSet的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript WeakMap

JavaScript WeakMap

ES6 中的 SetMap 和 WeakMap

EcmaScript5 中的 WeakMap 实现?

javascript新增加的数据结构: Set Map WeakSet WeakMap

《javascript高级程序设计》学习笔记 | 6.5.WeakMap