手写一个深拷贝
- 递归
- 判断类型
- 检测循环引用(环)
不可能拷贝 proto
const cache = new Map()//缓存已拷贝部分 function clone(object){ if(cache.get(object)){//假如已缓存,直接返回 return cache.get(object) } let result if(! (object instanceof Object) ){//基础类型直接返回 return object }else if(object instanceof Array){ result = [] }else if(object instanceof Function){ result = function(){return object.apply(this,arguments)} }else if(object instanceof Date){ result = new Date(object-0) } else if(object instanceof RegExp){ result = new RegExp(a) }else{ result = {} } cache.set(object,result)//插入缓存 for(let key in object){ if(object.hasOwnProperty(key)){//非继承属性 result[key] = clone(object[key]) } } return result }
版权声明:本博客所有文章除特殊声明外,均采用 CC BY-NC 4.0 许可协议。转载请注明出处 Roxas Deng的博客!