继承的另一种实现方式- 通过复制属性实现继承

 1 <!DOCTYPE HTML>
 2 <html>
 3 <head>
 4     <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 5     <title>通过复制属性实现继承</title>
 6 
 7 </head>
 8 <body>
 9 
10     <script type="text/javascript">
11         
12     var P = {
13         name : [1, 2, 3],
14         age : {
15             aa : "s",
16             bb : "t"
17         }
18     };
19     var child = {},i;
20 
21     for(var k in P){
22         if(P.hasOwnProperty(k)){
23              child[k] = P[k];    //child[name] = [1, 2, 3];
24         }
25     }
26 
27     console.log(child);
28     console.log(child.name);
29     child.name.push(4);
30     console.log(P.name);        //[1, 2, 3, 4]  -->  改变了子对象 也改变了父对象!!
31 
32 
33 
34     //深度复制
35     function extendDeep(parent, child){
36         var i,
37             toStr = Object.prototype.toString,
38             astr = "[object Array]";
39 
40         child = child || {};
41 
42         for(i in parent){
43             if(parent.hasOwnProperty(i)){
44                 if(typeof parent[i] === "object"){
45                     /*
46                      *    那么为什么要分数组跟对象两种情况呢?
47                      *    因为if 是数组--> 初始化仍旧是{} 则 得到的是一个对象 如: {0: 1, 1: 2, 2 : 3}
48                      *    所以要先正确的初始化
49                      *    这就是跟浅复制 的 某方面的区别 浅复制 只需要引用复制即可<浅复制只复制了一层>
50                     */
51                     child[i] = (toStr.call(parent[i]) === astr) ? [] : {};   
52                     console.log("i-->:",i);
53                     console.log("parent[i]::",parent[i]);
54                     extendDeep(parent[i], child[i]);
55                 }else{        //直到子 不是对象的时候 此时复制的是值 不是对象
56                     child[i] = parent[i];
57                     console.log(child[i]);
58                 }
59             }
60         }
61 
62         return child;
63     }
64 
65     var dad = {
66         counts : [1,2,3],
67         reads : {paper : true}
68     };
69 
70     var kid = extendDeep(dad);
71 
72     console.log(kid.counts);
73 
74     kid.counts.push(4);
75     console.log(kid.counts.toString());        //1,2,3,4
76     console.log(dad.counts.toString());        //1,2,3
77 
78     console.log(dad.reads === kid.reads);    //false
79     kid.reads.paper = false;
80 
81     kid.reads.web = true;
82     console.log(dad.reads.paper);    //true
83     console.log(dad.reads.web);        //undefined
84     </script>
85 </body>
86 </html>
疯癫不成狂,有酒勿可尝;世间良辰美,终成水墨白。
原文地址:https://www.cnblogs.com/chuyu/p/3291764.html