JS设计模式(一)Mixin classes

本文介绍了如何使用Mixin类实现类间方法的共享,无需通过传统的继承关系。文章详细解释了增强函数augment的工作原理及使用方法,并对比了传统继承方式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值