前言
我在处理一个复杂对象的深拷贝方法时接触到WeakMap
, 其作为缓存结构以解决对象内部的循环引用问题. 为了改造这个方法, 决定研究WeakMap
.
一、为何选用WeakMap
WeakMap
和Map
都可以使用对象作为键, Map
也可以使用基本数据类型作为键, 在特殊的情况下(都使用对象作为键), 两者看起来并无差别.
1. Map
Map
会阻止JavaScript
的内存回收机制对 以一个已经被回收的对象作为键的元素
进行回收.
与Map
内存储元素的方式有关:
A map API could be implemented in JavaScript with two arrays (one for keys, one for values) shared by the four API methods.
`map`在JavaScript内可通过使两个数组被4种方法共享来实现, 向`Map`内设置元素时分别将键和值`push`进这两个数组.
Setting elements on this map would involve pushing a key and value onto the end of each of those arrays simultaneously.
访问`Map`取值时需要遍历, 从两个数组内找到匹配的值.
var sayings = new Map();
sayings.set('dog', 'woof');
sayings.set('cat', 'meow');
sayings.set('elephant'