THE PASZ.COM BLOG

Wednesday, August 10, 2005

Coding Style: Getting into JavaScript OOP

I'm amazed how many JavaScript developers still don't use classes and other OOP concepts in their work. I don't know if this is because most of their projects are small in scale, or because most JavaScript developers come from a design background, or because OOP syntax in JS is arcane (e.g.: prototype). In any case, I think moving in an OOP direction is essential fro JS coders hoping to create more complex , maintainable applications.

For me, the best way to learn how to implement OOP is to convert non-OOP code. Create the functionality for a single instance of your object, using
variables and functions. Test it and get it working properly. Then convert
it into a Class. The variables become properties, and the functions become
methods. Once your Class is complete, it's very easy to create and test
multiple instances of the Object.

Here's a simple example with some non-OOP code that creates a single Rectangle:


var x = 100;
var y = 200;
var width = 50;
var height = 60;
function perimeter(){...} //returns perimeter
function area(){...} //returns area


To turn it into a Class, just make
x,y,width and height the properties, and perimeter() and area() the methods.


//Rectangle class
function Rectangle(x, y, width, height){
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}

Rectangle.prototype.area = function(){...}
Rectangle.prototype.perimeter = function(){...}
//end class


Voila, now you have a Class and you can instantiate multiple Rectangle
objects like so:

var r = new Rectangle(100,200,50,60);

This is a simplisitic example, but hopefully you get the idea. I like
coding out a single object procedurally first because it helps me understand in advance how my Class should be designed. Once you get good at making Classes, you
can skip this step, and do it in your head or on paper.

For further discussion of OOP techniques in JavaScript, I recommend my article A Practical Approach for Implementing Inheritance in JavaScript.