// 新增一个WeakMap来存储已经拷贝过的对象,来解决循环引用的问题(不存在同级引用的问题)
// 存在的问题:Function 是直接赋值引用,不是深拷贝
const wm = new WeakMap()
function deepCopy(target) {
let result = null
// 1.基本数据类型 Number String Boolean Undefined 和 Null
if (typeof target !== 'object' || target === null) {
return target
}
// 2.数组
else if (target instanceof Array) {
result = []
target.forEach(value => result.push(deepCopy(value)))
}
// 3.Date
else if (target instanceof Date) {
result = new Date(target)
}
// 4.RegExp
else if (target instanceof RegExp) {
result = new RegExp(target)
}
// 5.Object
else {
if (wm.has(target)) {
result = wm.get(target)
} else {
result = {}
wm.set(target, result)
for (let k in target) {
result[k] = deepCopy(target[k])
}
}
}
return result
}
// deepCopy() 的测试
const a = {
num: 123,
say() {
return 'Hello';
},
arr: [1, 2, [4, { name: 'Jack' }]],
n: null,
un: undefined,
d: new Date(),
reg: /[a-z0-9]+/,
b: {
c: {
d: null
}
}
}
a.b.c.d = a
const e = deepCopy(a)
a.num = 456
console.log(a);
console.log(e);
其它问题:Function的深拷贝?原型上的属性如何拷贝?