Q3:JS浅拷贝和深拷贝

浅拷贝

拷贝一层,深层次对象级别的只拷贝引用

  • Object.assign()
1
2
3
4
5
6
7
8
9
10
11
12
13
var obj1 = {
a: "hello",
b: {
a: "hello",
b: 21
}
};

var cloneObj1 = Object.assign({}, obj1)
cloneObj1.a = "changed"
cloneObj1.b.a = "changed"
console.log(obj1.a) //hello
console.log(obj1.b.a)

深拷贝

拷贝多层,每一层的数据都会被拷贝

  • 序列化和反序列化
1
2
var obj1 = { body: { a: 10 } }
var obj2 = JSON.parse(JSON.stringify(obj1))
  • Object.create()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function deepClone(initalObj, finalObj) {    
var obj = finalObj || {}
for (var i in initalObj) {
var prop = initalObj[i] // 避免相互引用对象导致死循环,如initalObj.a = initalObj的情况
if(prop === obj) {
continue;
}
if (typeof prop === 'object') {
obj[i] = (prop.constructor === Array) ? [] : Object.create(prop)
} else {
obj[i] = prop
}
}
return obj
}