JS設計模式(一)Mixin classes

Mixin classes provide a way to have objects and classes share methods without being in
a parent-child relationship. It should be used where you have general-purpose methods that
you want to share among several dissimilar classes. It is possible to share all of the methods in
a mixin class, or just a few of them, using the augment function.
 
Mixin classes提供了一種分享類方法的方式。這種分享是沒有父子繼承關係的。
 
將基類的方法放在一個沒有構造函數的類中。使用augment的方法將其複製到其他之類中。
  1. /* Augment function, improved. */
  2. function augment(receivingClass, givingClass) {
  3.     if(arguments[2]) { // Only give certain methods. 繼承個別方法 
  4.         for(var i = 2, len = arguments.length; i < len; i++) {
  5.                 receivingClass.prototype[arguments[i]] = givingClass.prototype[arguments[i]];
  6.                 }
  7.             }
  8.             else { // Give all methods. 繼承所有 
  9.             for(methodName in givingClass.prototype) {
  10.                 if(!receivingClass.prototype[methodName]) {
  11.                     receivingClass.prototype[methodName] = givingClass.prototype[methodName];
  12.                 }
  13.         }
  14.     }
  15. }

用法是 augment(Author, Mixin, 'serialize');

 

傳統意義上的繼承如下:
  1. function CliBase(){};
  2.  function CliUser(){
  3.   CliBase.call();
  4.   this.name;
  5.  }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章