es6 Mixin 模式的实现

Mixin 模式的实现

ES6 Mixin 指的是多个对象合成一个新的对象,新对象具有各个组成成员的接口。它的最简单实现如下。

 
 
  1. const a = {
  2. a: 'a'
  3. };
  4. const b = {
  5. b: 'b'
  6. };
  7. const c = {...a, ...b}; // {a: 'a', b: 'b'}

上面代码中,c对象是a对象和b对象的合成,具有两者的接口。

下面是一个更完备的实现,将多个类的接口“混入”(mix in)另一个类。

 
 
  1. function mix(...mixins) {
  2. class Mix {}
  3. for (let mixin of mixins) {
  4. copyProperties(Mix, mixin); // 拷贝实例属性
  5. copyProperties(Mix.prototype, mixin.prototype); // 拷贝原型属性
  6. }
  7. return Mix;
  8. }
  9. function copyProperties(target, source) {
  10. for (let key of Reflect.ownKeys(source)) {
  11. if ( key !== "constructor"
  12. && key !== "prototype"
  13. && key !== "name"
  14. ) {
  15. let desc = Object.getOwnPropertyDescriptor(source, key);
  16. Object.defineProperty(target, key, desc);
  17. }
  18. }
  19. }

上面代码的mix函数,可以将多个对象合成为一个类。使用的时候,只要继承这个类即可。

 
 
  1. class DistributedEdit extends mix(Loggable, Serializable) {
  2. // ...
  3. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值