Problem is introduced into

var person1 = {
	name: 'Joe'.age: "22"
}
var person2 = person1;
Copy the code

We want to copy person1’s attributes to Person2, and assignment is the easiest thing to do, but this is not what we want. Because this simply points person1 and Person2 to the same object, modifying one will affect each other

Object shallow copy

var person1 = {
	name: 'Joe'.age: 22.son: {
		name: 'Zhang Xiaosan'.age: 1}}var person2 = {};
for (var key in person1) {
	person2[key] = person1[key];
}
Copy the code

The loop takes the attributes of person1 and assigns them to person2. For attributes of the original type, they do not interact and can be copied successfully, but for attributes of the reference type, such as person2.son and person1.son, which point to the same object, modifying one of them affects each other

If attributes on the Person1 stereotype chain are not required, use hasOwnProperty() to determine when assigning

Object deep copy

A shallow copy copies a reference to a value, not a copy. Changing one will affect each other. We can also loop the reference value in the property and copy it to the property of the target object

Recursive implementation:

var person1 = {
	name: 'Joe'.age: 30.son: {
		first: {
			name: 'a little'.age: 3}}}function deepClone(origin) {
    var target = Array.isArray(origin) ? [] : {};
    for (var key in origin) {
        if(! origin.hasOwnProperty(key))continue;
        if (typeof origin[key] === 'object') {
            target[key] = deepClone(origin[key]);
            continue;
        }
        target[key] = origin[key];
    }
    return target;
}

var person2 = deepClone(person1);
person2.son.sencond = {
	name: 'small 2'.age: 2
}
console.log(person2);
console.log(person1);
Copy the code

Person2 contains all of the attributes of Person1, and modifications to the original value attributes are made without interaction

For objects that have no function properties, you can convert them to a string and then to an object using the json. parse method and json. stringify, resulting in a new, unrelated object