From bc2add263e9d74f91e1e29327bf848339e5fc3db Mon Sep 17 00:00:00 2001 From: mhrooz Date: Fri, 21 Jun 2024 22:40:45 +0200 Subject: [PATCH] update weakmap and weakset --- 5.7weak/t.js | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 5.7weak/t.js diff --git a/5.7weak/t.js b/5.7weak/t.js new file mode 100644 index 0000000..150cccc --- /dev/null +++ b/5.7weak/t.js @@ -0,0 +1,48 @@ +console.log("js garbage recyle"); +let john = {name: "John"}; +john = null; +console.log(john); + +john = {name: "John"}; +array = [john]; +john = null; +console.log(`array[0]: ${array[0].name}`); + +console.log("==========WeakMap=========="); +console.log("WeakMap must use obj as keys in map, the string or other primitive values are not allowed"); +let weakMap = new WeakMap(); +let obj = {}; +weakMap.set(obj, "ok"); +console.log(`weakMap.set(obj, "ok");`) +console.log(`weakMap.get(obj): ${weakMap.get(obj)}`) +//weakMap.set("test", "Whoops"); +console.log("If we use an object as the key, and this object has no other references to that obj, it will be removed from the memory automatically"); + +console.log(`obj = null`) +obj = null; +console.log(`obj has been removed from the memory`) +console.log(`obj cannot be used in map as well`) + +console.log(`weakmap only has four methods: + weakMap.set(key, value) + weakMap.get(key) + weakMap.delete(key) + weakMap.has(key)`) + +console.log(`Useage: if the obj dies, the secret disappears: + weakMap.set(john, "secret documents);`) + +let visitsCountMap = new Map(); + +function countUser(user){ + let count = visitsCountMap.get(user) || 0; + visitsCountMap.set(user, count + 1); +} + +console.log(`weakset only has three methods: + weakSet.add(key) + weakSet.delete(key) + weakSet.has(key)`) + +console.log(`both weakset and weakmap has no length/size method`) +