Object Oriented JavaScript -2

Continuing from my first post about this topic, where I mentioned why we need OO JS. First of all let me see what do we picture the moment we say that a language is OO. Here are some basic necessities of OO
Encapsulation: Usage of Classes and Objects
Inheritance: Extending Classes, Overloading methods
Polymorphism: Same method with different number of arguments

Now without wasting further time, lets get on with how these OO principles can be applied to JS

Creating Objects in JS

1. Using Inbuilt Object type:

var myRectangle=new Object();
myRectangle.length=2;
myRectangle.breadth=4;

myRectangle.area=function()
{
return (myRectangle.length*myRectangle.breadth);
}

alert(“area:”+myRectangle.area());

2. The JSON (JavaScript Object Notion) way
var myRectangle2={
length:2,
breadth:4,
area:function()
{
return(this.length*this.breadth);
}
};

alert(“area2:”+myRectangle2.area());

Creating Classes in JS

You might argue that so far we have only created Objects, but in an OO language we first create a class and then create object. Well, that is very much possible in JS as well.

The good news is, that in JS, functions can be treated as classes. How? Let’s check this example.

//Creating a class in JS
function rectangle(length, breadth)
{
this.length=length;
this.breadth=breadth;
this.area=setArea;
this.perimeter=setPerimeter;

this.test=function()
{
alert(“hi! you are in test function”);
}

function setArea()
{
return (this.length*this.breadth);
}

function setPerimeter ()
{
return 2*(this.length+this.breadth);
}
}

var rec=new rectangle(2,6);
var areahere=rec.area();
alert(areahere);
alert(rec.perimeter());

var rec1=new rectangle(1,1);
var areahere=rec1.area();
alert(areahere);
alert(rec1.perimeter());
rec1.test();

More on OO JS (Inheritance and Polymorphism) later