Mixin @ JS

by Taleeb Anwar

JavaScript

if (typeof Object.prototype.addMixin !== 'function') {
  Object.defineProperty(Object.prototype, 'addMixin', {
    value: function addMixin(mixin) {
      mixin.call(this.prototype);
    },
    configurable: true,
    writable: true,
		enumerable: false
  });
}

var asCircle = (function() {
  this.area = function() {
    return Math.PI * this.radius * this.radius;
  };
  this.grow = function() {
    this.radius++;
  };
  this.shrink = function() {
    this.radius--;
  };
  return function() {
    this.area = area;
    this.grow = grow;
    this.shrink = shrink;
    return this;
  };
})();

var Circle = function(radius) {
  this.radius = radius;
};
Circle.addMixin(asCircle);
var circle1 = new Circle(5);
console.log(circle1.area());