js deep copy and shallow copy analysis and implementation

In js syntax, as basic types such as Number, String, Boolean, they are passed by value are passed by value, and the like objects {a: 10, b: 20 }, they pass values are quoted pass value
for objects, in here summarize the problems encountered deep copy and shallow copy.
Basic types are passed by value, such as: a = 10, b = a , the system allocates memory space for a different and B, no interaction between each other.
 

		var a = 10;
		var b = a;
		b = 20;
		console.log(a);   //输出结果为10
		console.log(b);   //输出结果为20

But for objects, the result is the opposite.
Shallow copy :

	   var obj1 = {
			a: 10,
			b: {
				a: 'yf',
				b: 'bl'
			},
			c: ['Bob','Tom','nick'],
			d: function(){
				console.log('Hello World');
			}
		};
		var obj2 = obj1;
		obj2.a = 30;
		console.log(obj1);
		console.log(obj2);
		console.log(obj1 === obj2);

Output:

I can clearly see from the above code block, obj1, obj2 refer to the same piece of memory space, I though we were obj2 assignment, equivalent to the entire memory space has been assigned, so obj1, obj2 have carried out modification, this is called a shallow copy.
Deep copy :
1, with JSON data parsing achieve deep copy.

// 使用JSON数据解析来实现深度拷贝(JSON不能够识别Function类型)
			var obj1 = {
				a: 10,
				b: {
					a: 'yf',
					b: 'bl'
				},
				c: ['Bob','Tom','nick'],
				d: function(){
					console.log('Hello World');
				}
			};
		function deepClone(obj){
			return JSON.parse(JSON.stringify(obj));
		}
		var e = deepClone(obj1);
		e.a = 20;
		console.log(e);
		console.log(obj1);
		// 通过类型检测判断JSON是不识别Function类型的
		console.log(typeof e.d);
		console.log(typeof obj1.d);

The resulting output is shown below:

Using JSON parsing data in this way is easier to understand, we use JSON.stringify to convert it to a JSON string, this time to re-generate the strings and the original object is nothing to do, that is a string a memory re-opened, then we use JSON.parse converted to an object, in this case operate on the old and new object are independent from each other, the results of our output is a value different.
** disadvantages: ** this method has a fatal error, is not able to recognize the type of object Function, the JSON.stringify () Function can not be identified, will return undefined, so this method can only be used for only the object data in. This method will abandon the object constructor, after a deep copy, no matter what the object's constructor that will turn it into Object.
To solve this problem, we use the recursive method to traverse the output of the object attributes.
2, recursive copy
 

	function deepClone(Obj1, Obj2) {    
  			var obj = Obj2 || {};    
  			for (var i in Obj1) {        
    			var prop = Obj1[i]; 
    			// 避免相互引用对象导致死循环,如initalObj.a = initalObj的情况
    			if(prop === obj) {            
      			continue;
    		}        
   			if (typeof prop === 'object') {
    			obj[i] = (prop.constructor === Array) ? [] : {};            
      			arguments.callee(prop, obj[i]);
    		} else {
      			obj[i] = prop;
    		}
  		}    
  		return obj;
	}
	var str = {};
	var obj = { a: {a: "hello", b: 21, c: function(){alert('hello world');}}};
	deepClone(obj, str);
	console.log(str.a);

Recursive method, we successfully solve the problems caused by Function, also avoids the situation in due time traversing the object call caused each other.
With words to the end of a difference between deep and shallow copy copy:
shallow copy is old and the new object reference the same memory space, a change is all changed, namely: a change all changed; deep copy of the old object reference is the original space, the new object the new space, control their own size.
 

Guess you like

Origin blog.csdn.net/qq_36742720/article/details/90449213