1 <!DOCTYPE html>
2 <html lang="en">
3 <head>
4 <meta charset="UTF-8">
5 <title>对象的深度克隆</title>
6 </head>
7 <body>
8 <script type="text/javascript">
9 // 深度克隆(复制)
10
11 function getObjClass(obj) {
12 let result = Object.prototype.toString.call(obj).slice(8, -1);
13 if(result === 'Null'){
14 return 'Null';
15 }else if(result === 'Undefined'){
16 return 'Undefined';
17 }else {
18 return result;
19 }
20 }
21
22 // 深度克隆
23 function deepClone(obj) {
24 let result, objClass = getObjClass(obj);
25 if(objClass === 'Object'){
26 result = {};
27 }else if(objClass === 'Array'){
28 result = [];
29 }else {
30 return obj; // 如果是其他数据类型不复制,直接将数据返回
31 }
32 // 遍历目标对象
33 for(let key in obj){
34 let value = obj[key];
35 if(getObjClass(value) === "Object" || 'Array'){
36 result[key] = deepClone(value);
37 }else {
38 result[key] = obj[key];
39 }
40 }
41 return result;
42 }
43
44
45 let obj3 = {username: 'kobe',age: 39, sex: {option1: '男', option2: '女'}};
46 let obj4 = deepClone(obj3);
47 console.log(obj4);
48 obj4.sex.option1 = '不男不女'; // 修改复制后的对象不会影响原对象
49 console.log(obj4, obj3);
50
51
52 </script>
53 </body>
54 </html>