码迷,mamicode.com
首页 > 编程语言 > 详细

javascript设计模式-掺元类

时间:2016-03-13 16:10:19      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

有一种重用代码的方法不需要用到严格的继承。如果想把一个函数用到多个类中,可以通过扩充的方式让这些类共享该函数。其实际做法大大体为:先创建一个包含各种通用方法的类,然后再用它扩充其他的类。这种方式就叫做掺元类

 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());

javascript设计模式-掺元类

标签:

原文地址:http://www.cnblogs.com/tengri/p/5272172.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!