Object Oriented JavaScript

Here are some notes from presentation I have recently given on Object Oriented JS (JavaScript)

Why do we need OO(Object Oriented) JS?

With the popularity of AJAX and similar technologies, role of JS has become relatively more important in Web applications. Earlier you could think of JS just as a facilitator for the actual web application. But now, a lot of coding is being done in JS, sometimes even more than 50% of the code is handled in JS. With more emphasis on usability and look and feel of the application, JS has taken center stage for web applications.

Another reason for JS popularity is because it is easy to code. You don’t need a special training for JS as with other languages like Java. This is because JS was originally meant for designers rather than developers. Now, because it is easy to code, it is easy to mess up too. You don’t have proper structure enforced while coding for JS. That is why need of properly structured OO JS is felt more now.

In addition to above stated reasons, one more concern with JS is that it is highly underused, there are a lot of functionality JS provides you which you don’t use (in many cases we are not even aware of a lot of possibilities JS has)

Traditional Usage of JS
For sake of simplicity, let me take an example where we try to calculate area of rectangle and a square. In traditional usage of JS, we will initially create a JS file and keep adding methods as per our requirements (mostly the JS files ends up in a mess)

Say initially you wanted a method to calculate area of rectangle, you created a method called area, then you wanted to calculate perimeter of teh same rectangle, and you added another method. Sometime later you want to calculate area of square. and so on

<script language=”JavaScript”>

//creating method for calculating rectangle area
function area(length, breadth)
{
return length*breadth;
}

var myArea=area(2,3);
alert(“area is :”+myArea);

//add a method for calculating perimeter
function perimeter(length, breadth)
{
return 2*(length+breadth);
}

var myPerimeter=perimeter(2,3);
alert(“myPerimeter is :”+myPerimeter);

//creating method for calculating square area
function square_area(side)
{
return side*side;
}

var myArea2=square_area(2,3);
alert(“square area is :”+myArea2);
</script>

Now my question is.. is this how we do code in any OO language like Java?

Nope. We will create our classes. We will use polymorphism. We will properly organize our code.

If you are already aware of what I am talking about, you can stop reading. If not, come back tomorrow, I will write more about it.

(..to be continued)