javascript類式繼承模式#2——借用構造函數

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>類式繼承模式#2——借用構造函數</title>
 6 </head>
 7 
 8 <body>
 9 <script type="text/javascript">
10 
11     function Article(){
12         this.tags=['js','ajax'];
13     };
14     
15     Article.prototype.say=function(){return this.tags;}
16     
17 /***************************************/
18     var article=new Article();
19 
20     function BlogPost(){};
21     
22     BlogPost.prototype=article;
23     BlogPost.prototype.say=111;
24     
25     var blog=new BlogPost();
26 
27     function StaticPage(){
28         Article.call(this);
29     };
30     StaticPage.prototype={
31         x:100,
32         y:function(){
33             return this.x;
34         }
35     }
36     
37 var page = new StaticPage();
38 
39 
40 //BlogPost的原型繼承了new Article(),即便在BlogPost.prototype上添加屬性方法,事實上仍是給Article構造函數添加屬性方法
41 console.log(blog);
42 
43 //將父類Article中的方法屬性繼承過來,其實就是拷貝過來,佔爲己有,而且能夠覆蓋父類中的屬性方法,但並無將父類的原型鏈拷貝過來;
44 console.log(page);
45 
46 //構造函數模式缺點:調用父構造函數的原型,子構造函數能獲取到父構造函數的屬性和方法,但卻未繼承父構造函數的原型,即父構造函數__proto__所保存的連接沒有繼承給子構造函數。
47 
48 //構造函數模式優勢:能夠複製父構造函數的屬性和方法,並不會出現子構造函數覆蓋父構造函數的意外風險,能實現多重繼承,能夠父子構造函數之間傳遞參數。
49 
50 
51 </script>
52 </body>
53 </html>
相關文章
相關標籤/搜索