create-mixin
Version:
Mix the prototype of one class into another
34 lines (29 loc) • 1.14 kB
JavaScript
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global = global || self, global.createMixin = factory());
}(this, (function () { 'use strict';
/**
* Creates a mixin for use in a class extends expression.
* @module create-mixin
*/
/**
* @alias module:create-mixin
* @param {class} Src - The class containing the behaviour you wish to mix into another class.
* @returns {function}
*/
function createMixin (Src) {
return function (Base) {
class Mixed extends Base {}
for (const propName of Object.getOwnPropertyNames(Src.prototype)) {
if (propName === 'constructor') continue
Object.defineProperty(Mixed.prototype, propName, Object.getOwnPropertyDescriptor(Src.prototype, propName));
}
if (Src.prototype[Symbol.iterator]) {
Object.defineProperty(Mixed.prototype, Symbol.iterator, Object.getOwnPropertyDescriptor(Src.prototype, Symbol.iterator));
}
return Mixed
}
}
return createMixin;
})));