const myObject = {
name: 'Harry',
talk: function() {
console.log('hello world')
}
}
myObject.myObject = myObject; // 循环引用
/**
* 乞丐版
* 无法拷贝函数、处理循环引用
*/
const deepClone0 = (obj) => JSON.parse(JSON.stringify(obj));
/**
* for-in
* 没有处理循环引用、函数没有深拷贝
*/
const deepClone1 = (obj) => {
if (typeof obj === 'object') {
let newObj = Array.isArray(obj) ? [] : {};
for (const key in obj) {
newObj[key] = deepClone1(obj[key]);
}
return newObj;
} else {
return obj;
}
};
const deepClone2 = (obj, map = new Map()) => {
if (typeof obj === 'object') {
let newObj = Array.isArray(obj) ? [] : {};
if (map.get(obj)) {
return map.get(obj);
}
map.set(obj, newObj);
for (const key in obj) {
newObj[key] = deepClone2(obj[key], map);
}
return newObj;
} else {
return obj;
}
};
const old = {a:1, b:{a:123}, c:[1,2,3], d:function(){console.log(1)}};
old.old = old;
const aa = deepClone2(old);
console.log(aa.d());
console