es6 怎样实现mixin
问题: 如何实现 mixin
-
解决办法:
function mix(...mixins){ class Mix {} for(let mixin of mixins) { copyProperties(Mix, mixin); copyProperties(Mix.prototype, mixin.prototype) } return Mix; } 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); } } }
-
使用方法:
class Sub extends mix(Loggable, Serializable){ }