const isComplexDataType = obj => (typeof obj === 'object' || typeof obj === 'function') && (obj !== null)
function deepClone(obj, hash = new WeakMap()) {
if (obj.constructor === Date) {
return new Date(obj)
}
if (obj.constructor === RegExp) {
return new RegExp(obj)
}
if (hash.has(obj)) return hash.get(obj)
const allDes = Object.getOwnPropertyDescriptors(obj);
const cloneObj = Object.create(Object.getPrototypeOf(obj), allDes);
hash.set(obj, cloneObj);
for (let key of Reflect.ownKeys(obj)) {
cloneObj[key] = (isComplexDataType(obj[key]) && typeof obj[key] !== 'function') ? deepClone(obj[key], hash) : obj[key]
}
return cloneObj;
}
const demo = {
a: 1,
da: new Date(),
re: /ds/,
func: function () { console.log('我是一个函数') },
[Symbol('1')]: 1,
test1: {
name: '123'
}
}
demo.loop = demo;
Object.defineProperty(demo, 'test', {
enumerable: false,
value: '不可枚举属性'
})
const copy = deepClone(demo);
console.log(copy);
copy.test1.name = 'test';
console.log(copy);
console.log(demo);