Last Updated: February 25, 2016
·
1.328K
· meddle0x53

Mixins in JavaScript - a simple way

As in my previous protip, I'm going to introduce the 'ex' helper function first:

function ex (destination, source) {
  var p;

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

Nothing special, just copies the source's properties into the destination.

And here is our mixin function:

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

Again nothing special - it takes 0+ mixin objects and using the helper 'ex' function adds their properties to the current context object.

Here is an example:

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

Foo.include = mixin;

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

This is our class foo, it can handle mixins (see how we assigned the 'mixin' function to be its 'include' method).

And let's mix some object in Foo:

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

Here we go:

var foo = new Foo(1, 2);

console.log(foo.c()); // 3
console.log(foo.e()); // 25

console.log(foo.constructor.prototype); 

Try it here

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside