Object Oriented Javascript

Posted on by 4 comments

I have been developing software using object oriented technologies since 1993 and I have recently found a way to apply the same techniques to JavaScript. I decided to share some of the techniques that I am using in my day to day work.

I must give credit where credit is due, none of this would be possible without the wonderfull javascript library prototype. Keep in mind that in Javascript there is no support for information hiding or encapsulation but using some of the techniques that I am going to describe you should be able to apply most OO techniques.

First and foremost is inheritance. Without inheritance, you have are forced to duplicate your code in many places (not forced but that seems to be the trend). Lets start with the simplest of examples, the classic shape hierarchy. Suppose you have a shape base class that has one method that is abstract (that is to say it does nothing) ‘getArea’ and you have several sub classes (Circle, Square, Triangle) that are also Shapes.

In java you would write something like this:

public abstract class Shape {
    private final String name;

    public Shape(String name) {
        this.name = name;
    }

    String getName() {
        return this.name;
    }
    abstract double getArea();
}

public class Circle extends Shape {
    public static final int PIE = 3.14;
    private final int r;

    public Circle(int r) {
        super("Circle");
        this.r = r;
    }

    public double getArea() {
        return PIE*this.r*this.r;
    }
}

public class Square extends Shape {
    private final int l;

    public Square(int l) {
        super("Square");
        this.l = l;
    }

    public double getArea() {
        return this.l*this.l;
    }
}

public class Triangle extends Shape {
    private int base;
    private int height;

    public Triangle( int base, int height) {
        super("Triangle");
        this.base = base;
        this.height = height;
    }

    public double getArea() {
        return 0.5d*this.base*this.height;
    }
}

An example usage of the hierarchy is:

 

Shape[] shapes = {new Circle( 4 ), new Square( 4 ), new Triangle( 3, 6 ) };
for ( int i=0; i <shapes.length(); i++) {
    System.out.println( shapes[i].getName() + " area is " + shapes[i].getArea() );
}

Now for the javascript:

 

var Shape = Class.create({
    initialize: function( name ) {
        this.name = name;
    },

    getArea : function() {
         throw( "You must implement the getArea method");
    },

    getName: function() {
         return this.name;
    }
});

var PIE = 3.14;
var Circle = Class.create( Shape, {
    initialize: function($super,r) {
        $super('Circle');
        this.r = r;
    },

    getArea: function() {
        return PIE*this.r*this.r;
    }
} );

var Square = Class.create( Shape, {
    initialize: function($super,l) {
        $super('Square');
        this.l = l;
    },

    getArea: function() {
        return this.l*this.l;
    }
} );

var Triangle = Class.create( Shape, {

    initialize: function( $super, base, height) {
        $super('Triangle');
        this.base = base;
        this.height = height;
    },

    getArea: function() {
        return 0.5*this.base*this.height;
    }
} );

And the usage in javscript

 

var shapes = [ new Circle(4), new Square(4), new Triangle(3,6) ];
for ( var i=0; i < shapes.length; ++i ) {
    alert( shapes[i].getName() + " area is " + shapes[i].getArea() );
}

As you can see the javascript code and java code are very close to each other. I hope this example helps you make the transition from java to javascript while maintaining many of your object oriented techniques that you have learned over the years.

4 comments on “Object Oriented Javascript

  1. Wow, with your long OO history, I see that you haven’t coded Java regularly. Knowing that you “extend” classes and that you initialize arrays with {} is pre-SCJP-level knowledge.

  2. Prototype is great. No doubt about that. But keep in mind that object oriented and class extension is also possible in native javascript.

    look at this example I made:
    http://jsbin.com/owelot/8/edit#javascript,html

    There you have a Person class that has two different implementations. In this case Person class acts as a JAVA abstract class (although in js you can actualy instanciate it).

  3. @Blaine
    I see you don’t know what your talking about. In my industry we have been initializing arrays with {}. And yes you do “extend” classes. The example that was given was textbook OO. If you read any Java OOP textbook you’ll find an example exactly like that. Also for your future information there is no such thing as “pre-SCJP-level knowledge”.

  4. Your example is a text book example of how to create and use objects in JavaScript.

    I am describing how you can create objects in JavaScript that look very similar to those created in Java. My example requires the PrototypeJS JavaScript library where your example requires nothing extra.

Leave a Reply

Your email address will not be published. Required fields are marked *