因为JSON实现的深拷贝不能满足特殊需求
const weakMap = new WeakMap();
function deepClone(origin) {
if (origin instanceof Set) return new Set([...origin]);
if (origin instanceof Map) return new Map([...origin])
if (typeof origin == 'symbol') return Symbol(origin.description);
if (typeof origin == 'function') return origin;
if (!isObject(origin)) return origin;
if (weakMap.has(origin)) return weakMap.get(origin);
const newVariable = Array.isArray(origin) ? [] : {};
weakMap.set(origin, newVariable);
for (const key in origin) newVariable[key] = deepClone(origin[key])
for (const key of Object.getOwnPropertySymbols(origin)) newVariable[key] = deepClone(origin[key]);
weakMap.delete(origin);
return newVariable;
};
function isObject(value) {
const valueType = typeof value;
return (value !== null) && (valueType == 'object' || valueType == 'function')
}
const s1 = Symbol('111');
const s2 = Symbol('222');
const obj = {
name: '苏苏',
age: 18,
friends: ['土狗', 'SharkDog'],
miss: {
name: '安安',
age: 16
},
[s1]: 'sss',
s2,
set: new Set([1, 2, 3]),
map: new Map([[1, 2], ['a', 'b']]),
};
obj.test = obj;
const newObj = deepClone(obj);
obj.miss.name = 'test';
obj.friends[0] = 'test';
console.log(obj);
console.log(newObj);