关于深拷贝浅拷贝,论坛上面又大量的文章可以去看,这里废话不多。直接实现深拷贝。
function deepClone(obj, hash = new WeakMap) { if (typeof obj !== 'object') return obj // 非对象类型 if (obj === null) return null // 排除null if (obj instanceof RegExp) return new RegExp(obj) if (obj instanceof Date) return new Date(obj) const newObj = new obj.constructor() if (hash.has(obj)) { // 防止重复引用,内存溢出 return hash.get(obj) } hash.set(obj, newObj) for (const key in obj) { if (obj.hasOwnProperty(key)) { newObj[key] = deepClone(obj[key], hash); } } return newObj}
注释
WeakMap结构的使用方式和Map结构一样:
let wm = new WeakMap();
两者都是使用new来创建实例。如果添加键值对的话,我们同样是使用set方法,不过键名的类型必须要求是引用类型的值,我们来看看:
let wm = new WeakMap();
//数组类型的键名
wm.set([1],2);
//对象类型的键名
wm.set({'name':'Zhangsan'},2);
//函数类型的键名
function fn(){};
wm.set(fn,2);
console.log(wm);
//打印:WeakMap {
[1] => 2,
Object {name: "Zhangsan"} => 2,
function => 2
从打印结果可以看出,以上类型的键名都可以成功添加到WeakMap实例中。