js寄生组合式继承的类式编程风格
寄生组合式是js原型继承中效率最高,最简洁的继承方式,很多js库就采用了这种方式,其要点是:属性定义只放在构造器里,方法定义在原型里,子类原型clone父类原型。不废话,直接上代码,测试。
common.js
1 /** 2 * 通用工具类 3 */ 4 "use strict"; 5 (function(){ 6 /* 7 * 在Function原型里添加一个define函数,功能是在一个函数原型里绑定一个函数 8 * name:函数名字 9 * func:函数 10 */ 11 Function.prototype.define=function(name,func){ 12 this.prototype[name]=func; 13 }; 14 /* 15 * 把一个函数和一个调用上下文绑定在一起 16 */ 17 Function.prototype.bind=Function.prototype.bind || function(context){ 18 return function(){ 19 this.apply(context,arguments); 20 }; 21 }; 22 23 /* 24 * 在Function原型里添加一个extend函数,功能是当前类(函数)继承另外一个类(函数),并且是单继承 25 * parentType:父类(函数) 26 * 实现:寄生组合式继承 27 */ 28 Function.prototype.extend=function(parentType){ 29 //克隆父类的原型 30 for(var i in parentType.prototype) 31 { 32 this.prototype[i]=parentType.prototype[i]; 33 } 34 //修改子类构造器 35 this.prototype.constructor=this; 36 }; 37 })(); 38 39 //测试 40 /* 41 * 定义类 42 */ 43 function Person(name,age) 44 { 45 this.name=name; 46 this.age=age; 47 } 48 49 //方法定义在原型中 50 Person.define('getName',function(){ 51 return this.name; 52 }); 53 54 //方法定义在原型中 55 Person.define('getAge',function(){ 56 return this.age; 57 }); 58 59 /* 60 * 定义类 61 */ 62 function Student(id,name,age) 63 { 64 //继承属性 65 Person.call(this,name,age); 66 this.id=id; 67 } 68 69 //继承 70 Student.extend(Person); 71 72 //扩展方法 73 Student.define('getId',function(){ 74 return this.id; 75 }); 76 77 //创建对象 78 var s=new Student('123','张三',23); 79 /* 80 * 调用测试,其中getName和getAge从Person中继承过来 81 */ 82 alert('姓名:'+s.getName()+",年龄:"+s.getAge()+",编号:"+s.getId()); 83 /* 84 * 结果:姓名:张三,年龄:23,编号:123 85 */