Sunday, June 3, 2012

Super.js

I wrote this small JavaScript Object-Oriented library while working on JotPot.

I know there are lots of frameworks/libraries out there that do something similar, but

  1. I couldn't find one that did exactly what I was looking for
  2. I wanted to learn more of JavaScript

... and so, I built my own.

This is the result:

https://github.com/vlad-alexandru-ionescu/super.js#superjs


Super.js is a helper library for cleaner OOP JavaScript. It allows you to use classes in a way closer to what you are familliar to in Python or Java.

Here is a usage example:


declareClass(
    function Mammal(hasHair, legs, arms, canSee) {
        this._hasHair = hasHaid;
        this._legs = legs;
        this._arms = arms;
        this._canSee = canSee;
    },

    function eat(food) {
        alert("Om nom nom...");
    },

    function sleep() {
        alert("Z Z Z z z z . . .");
    }
);

declareClass(
    function Dog(onLeash) {
        this._super.constructor(true, 4, 0, true);
        this._onLeash = onLeash;
    },

    extend(Mammal),

    function eat(food) {
        if (food.isDogFood()) {
            return this._super.eat(food);
        } else {
            throw "up";
        }
    }
);

declareClass(
    function Cat(canSee) {
        this._super.constructor(true, 4, 0, canSee);
    },

    extend(Mammal)
);

declarClass(
    function BabyCat(mommy) {
        this._super.constructor(false);
        this._mommy = mommy;
    },

    extend(Cat),

    function eat(food) {
        if (food.isFromMotherCat()) {
            alert("Meaaaw nom nom...");
        } else {
            throw "NO!"
        }
    }
);
And you use the classes as you would expect:

var myDog = new Dog(true);
myDog.eat(someFood);

var myCat = new Cat(true);
var myBabyCat = new BabyCat(myCat);
while(isDay()) {
    myBabyCat.sleep();
}

No comments:

Post a Comment