-
Notifications
You must be signed in to change notification settings - Fork 0
/
手写deepClone.html
105 lines (89 loc) · 2.72 KB
/
手写deepClone.html
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>TEST</title>
<style>
body {
padding: 16px 32px;
}
pre {
padding: 16px;
line-height: 1.5;
background-color: #f5f5f5;
}
</style>
</head>
<body>
<H3>深克隆 deepClone</H3>
<pre>
</pre>
<script>
function deepClone(obj, map = new Map()) {
if (!obj || typeof obj !== "object") {
return obj;
}
if (obj.nodeType && 'cloneNode' in obj) {
return obj.cloneNode(true)
}
var result;
switch (Object.prototype.toString.call(obj)) {
case "[object Array]":
result = [];
for (let v of obj) {
result.push(deepClone(v));
}
return result;
case "[object Object]":
result = obj.constructor ? new obj.constructor() : {};
// 处理循环引用
if (map.get(obj)) {
return obj;
}
map.set(obj, result);
for (const k in obj) {
result[k] = deepClone(obj[k], map);
}
return result;
case "[object Date]":
return new Date(obj.getTime());
case "[object RegExp]":
var flags = "";
if (obj.global) flags += "g";
if (obj.multiline) flags += "m";
if (obj.ignoreCase) flags += "i";
return new RegExp(obj.source, flags);
default:
return obj;
}
}
function Test(props) {
this.props = props;
}
var test = {
name: 'wangliang',
birth: new Date(),
pattern: /wangliang/gim,
container: document.body,
hobbys: ['book', new Date(), /aaa/gim, 111]
};
var source = new Test(test);
var clone = deepClone(source);
console.log(source.props.birth === clone.props.birth);
console.log(source);
console.log(clone);
const target = {
field1: 1,
field2: undefined,
field3: {
child: 'child'
},
field4: [2, 4, 8]
};
target.target = target;
console.log(deepClone(target))
</script>
</body>
</html>