-
Notifications
You must be signed in to change notification settings - Fork 0
/
深拷贝.js
49 lines (40 loc) · 768 Bytes
/
深拷贝.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
const depClone = (cloneObj) => {
if (typeof cloneObj !== 'object') {
return cloneObj
}
// typeof null -> Object
if(cloneObj===null){
return cloneObj
}
// Array instanceof Object -> true
let copyObj = cloneObj instanceof Array ? [] : {}
for (let key in cloneObj) {
let _obj = cloneObj[key]
switch (typeof _obj) {
case 'object':
copyObj[key] = depClone(_obj)
break
case 'function':
copyObj[key] = _obj.bind(copyObj)
break
default:
copyObj[key] = _obj
break
}
}
return copyObj
}
let obj1 = {
a: 1,
b: {
c: 2
},
d() {
console.log(this.b.c)
}
}
let cloneObj1 = depClone(obj1)
obj1.b.c = 3
console.log(obj1, cloneObj1)
obj1.d()
cloneObj1.d()