Mixin模式的设计理念和应用场景

版权声明:转载请注明出处 https://blog.csdn.net/qdmoment/article/details/85246878

Mixin是mix in的缩写,掌握这一点很重要。

mix 英 [mɪks]   vi&vt 混合,调配  

mix in : 把......混入

设计理念:在这里mix in是指 把多个对象混入到一个对象之中,即合成一个对象,合成之后的新对象具有各个组成成员的接口;

mix模式实现:

function mix(...mixins){
  class Mix{}
  for (let mixin of mixins){
    copyProperties(Mix.prototype,mixin)//实例属性
    copyProperties(Mix.prototype, Reflect.getPrototypeOf(mixin)); // 拷贝原型属性
  }
}

function copyProperties(target, source){
  for(let key of Reflect.ownKeys(source)){
    if(key !== 'constructor' && key !== 'prototype' && key !== 'name'){
      let desc = Object.getOwnPropertyDescriptor(source,key);
      Object.defineProperty(target,key,desc)
    }
  }
}

应用场景:多个子类合并使用,添加共有方法

猜你喜欢

转载自blog.csdn.net/qdmoment/article/details/85246878