JavaScript--对象继承(组合继承)

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6     <script>
 7         /**
 8          * 为什么需要原型以及原型的使用:
 9          * 1.原型也是一个对象,通过原型可以实现对象的属性继承
10          */
11 
12 
13         function Person(name,sex) {
14             this.name = name || "匿名";
15             this.sex = sex || "男";
16         }
17 
18         // 构造函数 - 学生
19         function Student(a,b,number) {
20             // 借用继承
21             // 继承Person的属性
22             Person.call(this,a,b);
23             this.number = number;
24         }
25 
26         // 借用继承的缺点:
27         // 通过原型对象添加属性/ 方法,无法顺利继承过来
28         // 因为call其实只会调用Person构造函数内部的属性
29         Person.prototype.sayHi = function () {
30             console.log("我是Person,我是男生");
31         }
32 
33 
34         // 原型继承:继承Person的原型方法
35         // 这句话可以让Student 从Person身上继承过来一些属性
36         // 原型继承的缺点: 暂时还改动不了从原型继承过来的属性/方法
37         Stuent.prototype = new Person();
38         // 由于实例对象没有constroctor,手动指向
39         Student.prototype.constructor = Person;
40 
41 
42 
43         var stu1 = new Student("小明","男","一号男主角");
44         console.log(stu1);
45         stu1.sayHi();
46         console.log(stu1.name);
47     </script>
48 </head>
49 <body>
50 
51 </body>
52 </html>

 

posted @ 2017-10-29 00:07  QinXiao.Shou  阅读(156)  评论(0编辑  收藏  举报