Mixins

Mixins in JavaScript a simple way

by meddle

JavaScript

function ex (destination, source) {
  var p;

  for (p in source) {
    if (source.hasOwnProperty(p)) {
      destination[p] = source[p];
    }
  }
  return destination;
}

function mixin () {
    var i, ln = arguments.length;
    for (i = 0; i < ln; i++) {
        ex(this.prototype, arguments[i]);
    }
};

function Foo (a, b) {
    this.a = a;
    this.b = b;
}

Foo.include = mixin;

Foo.prototype = {
    constructor: Foo,
    c: function () {
        return this.a + this.b;
    }
};

Foo.include({
    d: 5,
    e: function () {
        return this.d * this.d;
    }
});

var foo = new Foo(1, 2);

console.log(foo.c());
console.log(foo.e());

console.log(foo.constructor.prototype);