The method of object copy is a difficult point, especially deep copy. It is recommended to run the code to help understand the copy.
1. json method
-
Suitable situation:
Deep clone of JSON object. The method is to first convert JSON.stringify() to a json string, and then JSON.parse() to a json array -
Disadvantages:
a. If there are functions in your object, the function cannot be copied.
b. The properties and methods on the prototype chain of the copyObj object cannot be copied .
var obj = {
x: 1,
y: {
a: 1,
b: 0,
c: [1, 2, 3]
}
};
// 相同的引用
var obj2 = obj;
console.log(obj2 == obj); //true 直接复制只是复制对象的指针,还指向同一个对象
//不同的引用
var obj3 = JSON.parse(JSON.stringify(obj));
console.log(obj3 == obj) //false 通过json方法复制后的地址不一样
console.log(obj3);