Deep clone (copy)

Preface: As we said at the beginning of the last article, making changes to one object does not affect the other. However, it is clear that when sex in obj1 is changed in shallow cloning (because sex is an array, it is a reference type, and it is an object in heap memory), sex in obj2 is also changed. This is not the effect we want, so deep cloning is to solve this problem.

Premise: Deep cloning is slightly more difficult than shallow copy, so read this article to understand JavaScript prototypes and how these methods work.

Object.hasOwnProperty(prop)

Object.prototype.toString()

Function.prototype.apply()

Function.prototype.call()

How to apply, you can go to the major blog community or MDN,javaScript elevation design look

Example:

<script type="text/javascript">
	// Deep clone:
	var obj = {
		name : 'abc'.// (original value)
		age : 18.// (original value)
		card : ['visa'.'master'].// Array (reference values)
		wife : {// Object (reference value)
			name : 'Tom'.son : {
				name: 'mySon'}}};var obj1 = {};
// For (var prop in obj) array can also be for in
Typeof () typeof();
//2, check whether it is an array or an object
// create the corresponding array or object

function deepClone(origin,target) {
	var target = target || {},
		toStr = Object.prototype.toString,// Use toString() to detect object types
		arrStr = '[object Array]';
	for(var prop in origin){
		if (origin.hasOwnProperty(prop)) {// Check if it is on the prototype, return false if it is
			if(origin[prop] ! = ='null' && typeof(origin[prop]) == 'object') {
				if(toStr.call(origin[prop]) == arrStr){
				[object Array]
					target[prop] = [];
				}else{
					target[prop] = {};
				}
				deepClone(origin[prop],target[prop]);// Recursive operation
			}else{ target[prop] = origin[prop]; }}}return target;
}

// Use the ternary operator to simplify the code as follows:
	function deepClone(origin,target) {
	var target = target || {},
		toStr = Object.prototype.toString,
		arrStr = '[object Array]';
	for(var prop in origin){// Iterate over the object
		if (origin.hasOwnProperty(prop)) {// Check if it is on the prototype, return false if it is
			if(origin[prop] ! = ='null' && typeof(origin[prop]) == 'object') {
				target[prop] = toStr.call(origin[prop]) == arrStr? [] : {};
				deepClone(origin[prop],target[prop]);// Recursive operation
			}else{ target[prop] = origin[prop]; }}}return target;
}
</script>
Copy the code

Simplified code:

Use the stringify() and parse() methods in JSON objects

<script type="text/javascript">
	var book = {
	    title: "professional javaScript".authors: [
	        "qietuzai"."qietuzai"].edition: 3.year: 2019.name: undefined.// Does not output, only instance properties of valid JSON data types
	};
	
	var copyBook = JSON.parse(JSON.stringify(book));
	console.log(copyBook);
	book.title = "I'm a base data type.";
	book.authors.push("I'm a reference data type");
	console.log(book);
</script>
Copy the code