Object Oriented JavaScript -3

In the last post I talked about how to create objects and classes in JS. The next step is to go for Inheritance.

Continuing from our previous examples, let’s say you want to create a class for rectangle

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);
}
}

let’s save the above code in a file called rectangleScript.js

Now there is a HTML file where you want to use this JS file code. You will simply add

<script type=”text/javascript” src=”rectangleScript.js” language=”javascript”></script>

Next let’s say you want to add some properties and methods to this already existing class. The ‘prototype’ keyword of Java comes into help here.

<script type="text/javascript" src="rectangleScript.js" language="javascript"></script>
<script language="JavaScript">
rectangle.prototype.color="red";
rectangle.prototype.setColor=function(color)
{
this.color=color;
}

rectangle.prototype.isSquare=function()
{
if(this.length==this.breadth)
return true;
else
return false;
}

var rec=new rectangle(2,6);
alert("area here:"+rec.area());
alert("is it a square:"+rec.isSquare());

alert("color:"+rec.color);
rec.setColor("yellow");
alert("color:"+rec.color);

var rec1=new rectangle(3,3);
alert("area here:"+rec1.area());
alert("is it a square:"+rec1.isSquare());
alert("color:"+rec1.color);

</script>

You might still argue that we have not actually inherited a class by another class, this is just adding properties. Yes, even inheriting a class by another is possible in JS. Again prototype keyword is the magic word. Additionally, we will see how method overloading works with JS. Look at this example

<script type="text/javascript" src="rectangleScript.js" language="javascript"></script>

<script language="JavaScript">

function goldenRectangle(length, breadth, someProperty)
//rectangle with length/ breadth=1.618
{
//this.rectangle=new rectangle(length, breadth);

this.length=length;
this.breadth=breadth;
this.newProperty=someProperty;
}

goldenRectangle.prototype =new rectangle();

//Method Overloading

goldenRectangle.prototype.test=function()
{
alert("hi! you are in goldenRectangles test function");
}

var myGoldenRectangle=new goldenRectangle(10,6,1);
alert("area:"+myGoldenRectangle.area());
alert("test property:"+myGoldenRectangle.newProperty);
myGoldenRectangle.test();
</script>