The difference between deep copy (cloning) and shallow copy (cloning), and the encapsulation of native js deep clone

Before, deep copy and shallow copy have always been a headache. When I see these words, I feel worried. So I kept checking the information, checking the information, checking the information. . . Fortunately, it is now clear. I write it here hoping to help people who have the same doubts as me, and also to prevent myself from forgetting and worrying again in the future. For shallow copy and deep copy, please see the italicized part for the biggest difference between them, and we will understand them one by one below.

    1. What is a copy?

       Answer: A copy is what we often call copying or cloning an object. The copy is divided into shallow copy and deep copy.

     Two.. What is a shallow copy?

      Answer: Shallow copy is a copy of the memory address, so that the 'copied' and 'original' point to the same memory address, it is just a simple reference to the object , only one layer can be copied, and sub-objects cannot be copied . As a result, the two objects before and after the copy affect each other, even if you change and I change, this is very bad in the actual development process. If you still don't understand, take a look at the following example:

1. Common objects

     var obj={
     		name:'du',
     		age:21,
     		borther:{
     		    name:'rui',
     		    age:12
     		}
     	};
        var obj1 = obj;
        obj1.sex='女';
        console.log(obj1,obj);

        //打印出结果为:
        obj1:{name: "du", age: 21, borther: {…}, sex: "女"}

        obj:{name: "du", age: 21, borther: {…}, sex: "女"}

 

It can be seen that when obj1 changes, obj also changes accordingly. This limits a lot. . . .

2. Array object

         var arr=[1,2,3,{a:6}];
         var arr1=arr.concat();
         arr1[3].b=7;
         arr[3].c=8;
         console.log(arr,arr1);
//打印出结果为
 arr:  [1, 2, 3, {…}]0: 11: 22: 33: {a: 6, b: 7, c: 8}length: 4__proto__: Array(0)
 arr1: [1, 2, 3, {…}]0: 11: 22: 33: {a: 6, b: 7, c: 8}length: 4__proto__: Array(0)

It can be seen that the same is true in the array. . . . . This is shallow copy.

3. What is a deep copy?

Answer: Deep copy is to recursively copy and copy the sub-objects in the object . After copying, the two objects will not be affected by each other. Because they will have different addresses, will have different memory in the heap, the short summary is to have the same value, but different addresses. Write an example below, and it will be clearer if you take JSON.parse()/JSON.stringify().

  var obj={
     		name:'du',
     		age:21,
     		borther:{
     		    name:'rui',
     		    age:12
     		}
     	};
   //JSON.stringify()是将json对象转换为字符串型,JSON.parse()是将字符串转换为json对象
     	var obj1=JSON.parse(JSON.stringify(obj));
        obj1.sex='女';
        obj.borther.sex='男';
        console.log(obj1,obj);

  //打印出来结果为
  obj1:{name: "du", age: 21, borther: {…}, sex: "女"} //注意对象的属性
        borther:{name: "rui", age: 12}               //注意子对象borther的结果


  obj: {name: "du", age: 21, borther: {…}}          //注意对象的属性
        borther:{name: "rui", age: 12, sex: "男"}   //注意子对象borther的结果

It can be seen from this that when obj1 changes, obj does not change, and when obj changes, obj1 does not change, which is a deep copy.

4. Encapsulation of deep clone

Then after reading these, you must understand what is shallow copy, deep copy and the difference between them. But the shortcoming is that only the usage of json data is seen in the deep copy, so can you encapsulate a deep copy method? It really does, hahahahahaha, let’s see below

When implementing deep copy, you have to build a framework of thinking in your mind first, that is, how to do it and why. . .

1. There is no doubt that the object must be traversed first

2. Judging whether it is the original value typeof() -->object

3. Determine whether it is an array or an object (methods include instanceof / toString / constructor)

4. Create the corresponding array or object

5. Recursion

With these ideas, it is much easier to write code

function deepClone(origin ,target){
          var target = target||{};              //以防用户没传,默认是对象
          for(var prop in origin){
             //hasOwnProperty是用来判断某个属性是不是在对象自己的属性,它不会检测到原型链上去
             if(origin[prop]!==null&&origin.hasOwnProperty(prop)){   //一定得确定对象上的属性不是原型链上的
                if(typeof(origin[prop])=='object'){    //判断是不是原始值
                  	   //在不是原始值的情况下,判断是数组还是对象
	           target[prop] = Object.prototype.toString.call(origin[prop])=='[object Array]'?[]:{};
	           deepClone(origin[prop],target[prop]);

                  }else{
                        target[prop]=origin[prop];
                  }
             }

          }
           return target;
      }
 var obj={
     		name:'du',
     		age:21,
     		borther:{
     		    name:'rui',
     		    age:12
     		}
     	};
var obj1=deepClone(obj,obj1);
        obj1.sex='女';
        obj.borther.sex='男';
        console.log(obj1,obj);
//打印结果为
obj1:   {name: "du", age: 21, borther: {…}, sex: "女"}  
        其中borther: {name: "rui", age: 12}
obj:    {name: "du", age: 21, borther: {…}}             
        其中borther: {name: "rui", age: 12, sex: "男"}

It can be seen from this that they do not affect each other. A deep copy completes the encapsulation.

Guess you like

Origin blog.csdn.net/du111_/article/details/86651331