Sunday 15 September 2013

"Comb" Library: Object Oriented

The comb library is a very useful set of utilities that will help in your javascript projects and especially with Node applications.

In this set of quick overviews I am going to give a brief run down of the different areas covered in the library:
  1. Object Oriented
  2. Logging
  3. Utilities
  4. Flow control
*But before going on, I am not connected to this project. I only found it helpful.. On with the show!

Object Oriented: As javascript does not support the classical object orientated paradigm. Comb provides a function define that takes an object with an attribute named instance or static. So this attribute is your class definition.

let's roll out a short example:
Create our base class

var Mammal = comb.define({
 instance: {
  _type: "mammal",
  _sound: " *** ",
  constructor: function (options) {
   options = options || {};
   this._super(arguments);
   var type = options.type,
    sound = options.mammal;
   type && (this._type = type);
   sound && (this._sound = sound);
  },
  speak: function () {
   return "A mammal of type " + this._type;
  }
 }
});

But wait Brian didn't you say there was a static attribute as well.
var Mammal = comb.define({
 instance: {
    ...
 },
 static: {
  DEFAULT_SOUND: " *** ",
  soundOff: function () {
   return "Im a mammal!!";
  }
 }
});

let's now create another class to inherit from our base class
var Wolf = Mammal.extend({
    instance: {
        _type: "wolf",
        _sound: "howl",
        speak: function () {
            return this._super(arguments) + " that " + this._sound + "s";
        },
        howl: function () {
            console.log("Hoooowl!")
        }
    }
});

let's take a look at this in action
var myWolf = new Wolf();
myWolf.howl() // "Hoooowl!"
myWolf.speak();// "A mammal of type wolf that howls"

For more reading here's the official documentation
... continue reading!