有一种重用代码的方法不需要用到严格的继承。如果想把一个函数用到多个类中,可以通过扩充的方式让这些类共享该函数。其实际做法大大体为:先创建一个包含各种通用方法的类,然后再用它扩充其他的类。这种方式就叫做掺元类。
1 function augment(receivingClass,givingClass){ 2 if(arguments.length > 2){ 3 for(var i= 2, len = arguments.length;i<len;i++){ 4 receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]]; 5 } 6 }else{ 7 for(var methodName in givingClass.prototype){ 8 if(!receivingClass.prototype[methodName]){ 9 receivingClass.prototype[methodName] = givingClass.prototype[methodName]; 10 } 11 } 12 } 13 } 14 15 function Author(name,books){ 16 this.name = name; 17 this.books = books; 18 } 19 Author.prototype.getBooks = function(){ 20 return this.books; 21 } 22 23 var MiXin = function(){}; 24 MiXin.prototype = { 25 serialize:function(){ 26 var output = []; 27 for(key in this){ 28 output.push(key + ":" + this[key]); 29 } 30 return output.join(", "); 31 } 32 } 33 augment(Author,MiXin); 34 var author = new Author("zap","读书笔记"); 35 console.log(author.serialize());
时间: 2024-11-05 23:37:18