Множественное наследование

by Artem

JavaScript

'use strict';

const log = console.log.bind(console);

const SerializableMixin = {
  serialize() {
    return JSON.stringify(this);
  }
};

const AreaMixin = {
  getArea() {
    return this.length * this.width;
  }
};

const mixin = (...mixins) => {
  var base = function() {};
  Object.assign(base.prototype, ...mixins);
  return base;
}

class Square extends mixin(AreaMixin, SerializableMixin) {
  constructor(length) {
    super();
    this.length = length;
    this.width = length;
  }
}

const x = new Square(3);
log(x.getArea()); // 9
log(x.serialize()); //{"length":3,"width":3}