1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta charset="UTF-8">
5 <title>javascript高级语法4-继承和聚合</title>
6 </head>
7 <body>
8 <script>
9
10 //继承
11 //创建人员类
12 function Person(name){
13 this.name = name;
14 }
15 //创建教师类
16 function Teacher(name,books){
17 //call方法可以将一个函数的对象上下文从初始化变成由this来决定。
18 //调用Person的构造函数,因为person没有new,所以是空对象。
19 Person.call(this,name);
20 this.books = books;
21 }
22 // 使教师类继承人员类
23 Teacher.prototype = new Person();
24 Teacher.prototype.constructor = Teacher;
25 Teacher.prototype.getBook = function(){
26 return this.name +" "+this.books;
27 }
28
29 //测试
30 var jim = new Teacher("JIm","extjs4");
31 //alert(jim.getBook());
32
33 // 创建extend函数为了程序中所有的继承操作
34 function extend(subClass,superClass){
35 //1.让子类的原型类属性等于父类的原型属性。
36 // 初始化一个中间空对象,为了转换子父类关系。
37 var F = function(){};
38 F.prototype = superClass.prototype;
39 //2.让子类继承F
40 subClass.prototype = new F();
41 subClass.prototype.constructor = subClass;
42 //3.为子类增加superClass属性
43 subClass.superClass = superClass.prototype;
44 //4.增加一个保险,就算原型类是超级类(Object)那么也要把你的构造函数级别降下来。
45 if(superClass.prototype.constructor = Object.prototype.constructor){
46 superClass.prototype.constructor = superClass;
47 }
48 }
49 //测试
50 function Author(name,books){
51 Author.superClass.constructor.call(this,name);//低耦合
52 //person.call(this,name) // 高耦合
53 this.books = books;
54 this.getBook = function(){
55 return this.name +" "+this.books;
56 }
57 }
58 //继承
59 extend(Author,Person);
60
61 var peter = new Author("张丹","javascript");
62 alert(peter.getBook());
63
64
65 //聚合
66 //第一种:原型上方法的聚合
67 //掺元类: 有时候不需要严格的继承,真正需要的是一个类(几个类)中的一些函数。
68 var JSON = {};
69 JSON.prototype = {
70 changeString:function(){
71 var output = [];
72 for(key in this){
73 output.push(key+"-->"+this[key]);
74 }
75 return output;
76 }
77
78 }
79 //制作聚合函数
80 function mixin(receivingClass,givingClass){
81 for(method in givingClass.prototype){
82 // 本类中没有这个函数情况下再聚合,否则跳过
83 if(!receivingClass.prototype[method]){
84 receivingClass.prototype[method] = givingClass.prototype[method];
85 }
86 }
87 };
88 //var o = {name:"zhangdan",age:27};
89 var o = function(){
90 this.name = "zhangsan";
91 this.age = 27;
92 }
93 mixin(o,JSON);
94 var a = new o();
95 document.write(a.changeString().join(","))
96
97
98
99 //第二种:类中的函数聚合
100 var JSON2 = {
101 toChange:function(){
102 var output = [];
103 for(key in this){
104 output.push(key+"--》"+this[key]);
105 }
106 return output;
107 }
108 }
109 //聚合函数
110 function mixin2(receivingClass,givingClass){
111 for(method in givingClass){
112 if(!receivingClass.__proto__[method]){
113 receivingClass.__proto__[method] = givingClass[method];
114 }
115 }
116 }
117 var s = {name:"zhangdan",age:30};
118 mixin2(s,JSON2);
119 document.write(s.toChange().join(","))
120 </script>
121 </body>
122 </html>