1.類的多種繼承,將多個類的接口“混入”(mix in)另一個類。
function mix(...mixins) { class Mix { // 如果不需要拷貝實例屬性下面這段代碼可以去掉 // constructor() { // for (let mixin of mixins) { // copyProperties(this, new mixin()); // 拷貝實例屬性 // } // } } 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); } } }
2.應用,上面代碼的mix
函數,可以將多個對象合成為一個類。使用的時候,只要繼承這個類即可。
class Lottery extends mix(Base, Calculate, Interface, Timer){ //... }
3.參考
http://es6.ruanyifeng.com/#docs/class-extends