zoukankan      html  css  js  c++  java
  • javascript设计模式-掺元类

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

     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());
  • 相关阅读:
    麦肯锡矩阵导航图
    以业务为核心的云原生体系建设
    万字长文拿下HTTP
    人人都该懂的埋点知识
    淘宝的技术架构
    五步,快速理解一个行业
    一文读懂用户分层
    python13day
    python12day
    python11day
  • 原文地址:https://www.cnblogs.com/tengri/p/5272172.html
Copyright © 2011-2022 走看看