Jovan Angelov Jovan Angelov - 1 month ago 6
Javascript Question

javascript prototype method

Simple javascript program to show which rectangle has bigger perimeter when button is clicked, but Rectangle.Perimeter doesn't seem to get the needed value from the Rectangle object for width and height. It just prints NaN instead of the perimeter.

<script>
function Rectangle(width, height) {
this.width = width;
this.height = height;
}
var Rectangle1 = new Rectangle(2, 4);
var Rectangle2 = new Rectangle(8.5, 11);

Rectangle.prototype.PrintRectangle = function () {
document.getElementById("p1").innerHTML = "Rectangle width is " + this.width + " and Rectangle height is "+ this.height;
};
Rectangle.prototype.RectanglePerimeter = this.width*2 + this.height*2;


function calculate() {
if(Rectangle1.RectanglePerimeter > Rectangle2.RectanglePerimeter){
document.getElementById("perimetar").innerHTML = "The biggest Rectangle has perimeter of " + Rectangle1.RectanglePerimeter;
}else{
document.getElementById("perimetar").innerHTML = "The biggest Rectangle has perimeter of " + Rectangle2.RectanglePerimeter;
}
}

</script>

<body>
<p><b>Paragraph no: 1</b></p>
<p id="p1" onload="Rectangle1.PrintRectangle()"></p>
<button id="button" onclick="calculate()">Calculate Perimeter</button>
<p id="perimetar"></p>
</body>

Answer
Rectangle.prototype.getPerimeter = function() { 
    return this.width*2 + this.height*2;
};

and then use

if(Rectangle1.getPerimeter() > Rectangle2.getPerimeter())
Comments