update weakmap and weakset
This commit is contained in:
		
							
								
								
									
										48
									
								
								5.7weak/t.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										48
									
								
								5.7weak/t.js
									
									
									
									
									
										Normal file
									
								
							| @@ -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`) | ||||||
|  |  | ||||||
		Reference in New Issue
	
	Block a user