zoukankan      html  css  js  c++  java
  • js深入研究之自定义混合Mixin函数

    <script type="text/javascript">
    /* 增加函数 */
    
    function augment(receivingClass, givingClass) {
      for(methodName in givingClass.prototype) { 
        if(!receivingClass.prototype[methodName]) {
          receivingClass.prototype[methodName] = givingClass.prototype[methodName];
        }
      }
    }
    
    /* 改进的增加函数 */
    
    function augment(receivingClass, givingClass) {
      if(arguments[2]) { // Only give certain methods.
        for(var i = 2, len = arguments.length; i < len; i++) {
          receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
        }
      } 
      else { // Give all methods.
        for(methodName in givingClass.prototype) { 
          if(!receivingClass.prototype[methodName]) {
            receivingClass.prototype[methodName] = givingClass.prototype[methodName];
          }
        }
      }
    }
    
    
    var Author = function Author(name, books) { // 构造函数
      this.name = name;
      this.books = books || 'default value';
    };
    
    Author.prototype = {
      getName: function() {
        return this.name;
      },
      getBooks: function() {
        return this.books;
      }
    };
    
    var Editor = function Editor() {
    };
    Editor.prototype = {
      hello: function() {
        return 'Hello,'+this.name;
      }
    };
    
    augment(Author, Editor);
    
    var author = new Author('Ross Harmes', ['JavaScript Design Patterns']);
    console.log(author.getName());
    console.log(author.getBooks());
    console.log(author.hello());
    </script>

    结果

    经过拼接处理之后,author就获取到了hello方法了,属性还是自己的name。

  • 相关阅读:
    二分查找
    「数学」二次函数中项系数大小与图像的关系
    「数学」夹角公式
    「CF80A」Panoramix's Prediction
    「Luogu P6101」[EER2]出言不逊
    「数学」三角函数公式以及部分证明
    「Luogu P6069」[MdOI2020] Group
    「CF80B」Depression
    「数学」Menelaus定理与Ceva定理
    「AT1175」ニコニコ文字列
  • 原文地址:https://www.cnblogs.com/jiqing9006/p/5059319.html
Copyright © 2011-2022 走看看