1. Implementation of Es5
var obj = {
name: "Zhang".age: 34.info: {
hobby: ["Football"."Basketball"."Table tennis"]}}function deepClone( resource ){
let target;
let type = Object.prototype.toString.call(resource).slice(8, -1);
if( typeof resource == "object" ){
target = type === "Array" ? [] : {};
for( let key in resource ){
if( resource.hasOwnProperty( key)){
if( typeof resource[key] =="object"){
target[key] = deepClone( resource[key] )
}else{ target[key] = resource[key]; }}}}else{
target = resource;
}
return target;
}
var newObj = deepClone(obj)
newObj.info.hobby[0] = "Pool";
console.log(obj,newObj)
Copy the code
2. Implementation of Es6
// The difference between map and wekMap:
Map keys can be arbitrary values. WekMap keys must be objects
// 2. The key of weakMap is a weak reference. After deleting the key, all references will be garbage collected
// hashMap: Avoid dead recursion when objects reference each other
function deepClone(origin, hashMap = new WeakMap(a)) {
if ((origin == undefined) | | (typeoforigin ! = ="object")) {
return origin
};
// Check whether the current object has been copied (to avoid an endless loop caused by object references)
const hashKey = hashMap.get(origin);
if (hashKey) return hashKey;
// Create new objects or arrays using the constructor attribute
const target = new origin.constructor();
hashMap.set(origin, target);
for (let k in origin) {
if(origin.hasOwnProperty(k)) { target[k] = deepClone(origin[k], hashMap); }}return target;
}
var obj1 = {};
var obj2 = {};
obj2.obj1 = obj1;
obj1.obj2 = obj2;
//1. Dead recursion occurs when hashMap is not used
//2. Using the hashMap inner loop only fires twice
deepClone(obj2)
Copy the code