Fork me on GitHub

Mixins in JavaScript

This post has been updated at 09/07/2011.

Thanks to JavaScript flexibility it's incredibly easy to use mixins:

Thanks to JavaScript flexibility it's incredibly easy to use mixins:

var sys = require("sys");

var extend = function extend (another) {
  var prototype = this.__proto__;
  this.__proto__ = another;
  another.__proto__ = prototype;
  return this;
};

Object.defineProperty(Object.prototype, "extend", {value: extend });

var Model = new Function();

var SQLFindersMixin = {
  findBySQL: function (query) {
    sys.puts("Finding by SQL: " + query);
  }
};

Model.prototype.extend(SQLFindersMixin);

var instance = new Model();
instance.findBySQL("SELECT * from POSTS");

So how does it work? Well we simply inject another item into the prototype chain, so instead of Model.prototype -> Object.prototype we turn it into Model.prototype -> SQLFindersMixin -> Object.prototype. Easy and useful.

blog comments powered by Disqus
About

RSS

All Posts IT JavaScript Node.js mixins

Tags

GitHub projects

Twitter @botanicus

Recent Comments