function deepClone(obj) {
if(obj == null) return obj
if(obj instanceof Date) return new Date(obj)
if(obj instanceof RegExp) return new RegExp(obj)
if(typeof obj !== 'object') return obj
let cloneObj = new obj.constructor
for(let key in obj) {
if(obj.hasOwnProperty(key)) {
cloneObj[key] = deepClone(obj[key])
}
}
return cloneObj
}
function deepClone(obj, hash = new WeakMap()) {
if(obj == null) return obj
if(obj instanceof Date) return new Date(obj)
if(obj instanceof RegExp) return new RegExp(obj)
if(typeof obj !== 'object') return obj
if(hash.get(obj)) return hash.get(obj)
let cloneObj = new obj.constructor
hash.set(obj,cloneObj)
for(let key in obj) {
if(obj.hasOwnProperty(key)) {
cloneObj[key] = deepClone(obj[key], hash)
}
}
return cloneObj
}
let obj = {name: 1, addr: {x:100}}
let o = deepClone(obj)
obj.addr = {x:200}
console.log(o)
欢迎访问小程序:女友睡前故事~
