ES6 Map和WeakMap
1.Map的學習
a.Map的定義:“值-值”,更完善的Hash結構;
const m = new Map()
const o = { p: 'hello Map' }
m.set(o, 'content')
const m = new Map(o)
b.Map的例項屬性與操作方法
map.size
map.set(key, value)
map.get(key)
map.has(key)
map.delete(key)
map.clear()
遍歷方法 keys()/values()/entries()/forEach
2.WeakMap的知識點
a.WeakMap的鍵名所引用的物件是弱引用
let map = new Map()
let key = new Array(5)
map.set(key, 1)
map.delete(key)
key = null
const wm = new WeakMap()
let key = new Array(5)
wm.set(wm, 1)
key = null
WeakMap保持對鍵名所引用物件的弱引用,只要所引用的物件的其他引用被清除,垃圾回收機制就會釋放該物件所佔用的記憶體。
b.WeakMap的應用
1)在DOM物件上儲存相關資料
let wm = new WeakMap(), element = document.querySelector(".element")
wm.set(element, "data")
element.parentNode.removeChild(element)
element = null
2)資料快取
const cache = new WeakMap()
function countOwnKeys (obj) {
if (cache.has(obj)) {
return cache.get(obj)
} else {
const count = Object.keys(obj).length
cache.set(obj. count)
return count
}
}
3)私有屬性
const privateData = new WeakMap()
class Person () {
constructor (name, age) {
privateData.set(this, {name: name, age: age})
}
getName () {}
}
export default Person