ES6 Map & WeakMap All In One
ES6 Map & WeakMap All In One
Map
Map
的 key 可以是任何类型,且 key 是强引用的,不便于自动 GC,可能会出现内存泄漏问题;Map
的 key 是可枚举的, key 是可枚举的话,其列表将会受垃圾回收机制的影响,从而得到不确定的结果;
const m = new Map();
// Map(0) {}[[Entries]]No propertiessize: (...)__proto__: Mapclear: ƒ clear()constructor: ƒ Map()delete: ƒ delete()entries: ƒ entries()forEach: ƒ forEach()get: ƒ ()has: ƒ has()keys: ƒ keys()set: ƒ ()size: (...)values: ƒ values()Symbol(Symbol.iterator): ƒ entries()Symbol(Symbol.toStringTag): "Map"get size: ƒ size()__proto__: Object
Map;
// ƒ Map() { [native code] }
const map = new Map();
const obj = {
key1: 'value 1',
key2: 'value 2',
};
map.set(obj, obj);
// Map(1) {{…} => {…}}
map.set('obj', obj);
// Map(2) {{…} => {…}, 'obj' => {…}}
map.set('map', map);
// Map(3) {{…} => {…}, 'obj' => {…}, 'map' => Map(3)}
for (const [key, value] of map) {
console.log('key, value =', key, value);
}
// key, value = {key1: 'value 1', key2: 'value 2'} {key1: 'value 1', key2: 'value 2'}
// key, value = obj {key1: 'value 1', key2: 'value 2'}
// key, value = map Map(3) {{…} => {…}, 'obj' => {…}, 'map' => Map(3)}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
WeakMap
WeakMap
的 key 只能是Object
类型,且 key 是弱引用的,便于自动 GC,避免内存泄漏问题;WeakMap
的 key 是不可枚举的, 如果key 是可枚举的话,其列表将会受垃圾回收机制的影响,从而得到不确定的结果;
const vm = new WeakMap();
// WeakMap {}[[Entries]]No properties__proto__: WeakMapconstructor: ƒ WeakMap()delete: ƒ delete()get: ƒ ()has: ƒ has()set: ƒ ()Symbol(Symbol.toStringTag): "WeakMap"__proto__: Object
WeakMap;
// ƒ WeakMap() { [native code] }
const wm = new WeakMap();
const obj = {
key1: 'value 1',
key2: 'value 2',
};
for (let key of Object.keys(obj)) {
console.log(key);
}
// wm.set(obj, 'prop');
for (let key in obj) {
console.log('key =', key);
wm.set(obj, key);
// key2 覆盖了 key1 ✅
}
if(wm.has(obj)){
const temp = wm.get(obj);
console.log('temp =', temp);
}
// key = key1
// key = key2
// temp = key2 ✅
// wm.delete(obj);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap
Proxy
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy
// vue 3, 响应式系统, 使用 WeakMap 收集 effects 副作用函数,提高性能和自动GC,避免内存泄漏
refs
Symbol
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol
Symbol.toStringTag;
Symbol(Symbol.toStringTag)
Symbol.iterator;
Symbol(Symbol.iterator)
©xgqfrms 2012-2020
www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/14494893.html
未经授权禁止转载,违者必究!