Make notes if you don’t want to forget after studying
Parse (json.stringify ()) what are the problems with deep copy?
NaN
,Infinity
intonull
function
,symbol
,undefined
Property loss- The RegExp object becomes
An empty object
- The Date object becomes
string
- The untraversable property of Enumerable false is missing
Implement deep copy yourself
const isComplexDataType = obj= > (typeof obj === 'object' || typeof obj === 'function') && obj ! = =null
const getAllKey = obj= > [...Object.getOwnPropertyNames(obj), ...Object.getOwnPropertySymbols(obj)]
function deepClone ( source, hash = new WeakMap(a)) {
// Base type
if(! isComplexDataType(source)) {return source
}
/ / Date type
if (source instanceof Date) {
return new Date(source)
}
/ / the RegExp type
if (source instanceof RegExp) {
return new RegExp(source)
}
// function
if (typeof source === 'function') {
return new Function(`return ${source}`) (the)}// Judge circular references
if (hash.has(source)) return hash.get(source)
// Copy non-traversable properties
const allDes = Object.getOwnPropertyDescriptors(source)
// Handle stereotype attributes
const targetObj = Object.create(Object.getPrototypeOf(source), allDes)
const keys = getAllKey(source)
hash.set(source, targetObj)
/ / recursion
for( let key of keys ) {
targetObj[key] = isComplexDataType(source[key]) ? deepClone(source[key], hash) : source[key]
}
return targetObj
}
Copy the code