Created
February 27, 2019 16:12
-
-
Save thoamsy/6dd6f4b8da085841fd9131c33119199a to your computer and use it in GitHub Desktop.
JS 深拷贝
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function deepClone(obj, hash = new WeakMap()) { | |
if (obj !== Object(obj) || typeof obj === 'function') return obj; | |
if (obj instanceof Set) return new Set(obj); | |
if (hash.has(obj)) return hash.get(obj); | |
let result; | |
if (obj instanceof Date) { | |
result = new Date(obj); | |
} else if (obj instanceof RegExp) { | |
result = new RegExp(obj.source, obj.flags); | |
} else if (obj.constructor) { | |
result = new obj.constructor(); | |
} else { | |
result = {}; | |
} | |
hash.set(obj, result); | |
if (obj instanceof Map) { | |
obj.forEach((val, key) => result.set(key, deepClone(val, hash))); | |
} | |
return Object.assign( | |
result, | |
...Object.entries(obj).map(([key, val]) => ({ | |
[key]: deepClone(val, hash), | |
})), | |
); | |
} | |
const data = { | |
a: 1, | |
b() { | |
console.log(this.a); | |
}, | |
c: new Map([[1, 2], [3, { a: 2 }]]), | |
d: new Date('1998'), | |
}; | |
const copy = deepClone(data); | |
copy.c.get(3).b = 4; | |
console.log(copy, data); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment