原型链继承跟构造函数继承的区别

 1 /*
 2        借用构造函数
 3      */
 4 
 5     //Article
 6     function Article(){
 7         this.tags = ["js", "css"];
 8     }
 9     Article.prototype.getTags = function(){
10         return this.tags;
11     };
12 
13     var article = new Article();
14 
15     //BlogPost
16     function BlogPost(){}
17 
18     BlogPost.prototype = article;//原型继承
19     var blog = new BlogPost();
20 
21     //StaticPage
22     function StaticPage(){
23         Article.call(this);//不能继承已经添加到原型中的成员
24     }
25     var page = new StaticPage();
26 
27     console.log(article.hasOwnProperty("tags"));//true
28     console.log(blog.hasOwnProperty("tags"));//false
29     console.log(blog.hasOwnProperty("getTags"));//false
30     console.log(blog.getTags());//["js","css"]
31     console.log(page.hasOwnProperty("tags"));//true
32     console.log(page.hasOwnProperty("getTags"));//false
33     //console.log(page.getTags());//报错

 

转载于:https://www.cnblogs.com/chuyu/p/3296098.html

你可能感兴趣的:(原型链继承跟构造函数继承的区别)