深拷贝

113 阅读1分钟

const  _completeDeepClone = (target, weak = new WeakMap()) => {

if (target === null) return target

if (typeof target !== 'object') return target

const constructor = target.constructor

if (/^(Function|RegExp|Date|Map|Set)$/i.test(constructor.name)) return new constructor(target)

if (weak.get(target)) {

return weak.get(target)

}

const cloneTarget = new target.constructor();

weak.set(target, true)

for (prop in target) {

if (target.hasOwnProperty(prop)) {

cloneTarget[prop] = _completeDeepClone(target[prop], weak)

}

}

return cloneTarget

}

var obj = { name:1 };

obj.age=obj

console.log(_completeDeepClone(obj))