Defining Constructors

[Total: 0    Average: 0/5]

This file shows how to set up a constructor “Rec”.

Body Code:

<script type=text/javascript>
function RecX()          { return this.width}
function RecY()          { return this.height}
function RecArea()       { return   this.width *   this.height}
function RecPerimeter()  { return 2*this.width + 2*this.height}
function RecSetSize(x,y) { this.width =x;this.height=y}
function RecEnlarge(x)    { this.width*=x;this.height*=x}
function RecShrink()     { this.width/=2;this.height/=2}
function Rec(x,y) {
  this.width     = x
  this.height    = y
  this.area      = RecArea
  this.perimeter = RecPerimeter
  this.setSize   = RecSetSize
  this.enlarge   = RecEnlarge
  this.shrink    = RecShrink
  this.x         = RecX
  this.y         = RecY
}
var r = new Rec(2,2)
document.write("area of r("+r.x()+","+r.y()+")="+r.area()+"<BR>");
document.write("ENLARGE by 2<BR>");
r.enlarge(2)
document.write("area of r("+r.x()+","+r.y()+")="+r.area()+"<BR>");
document.write("ENLARGE by 5<BR>");
r.enlarge(5)
document.write("area of r("+r.x()+","+r.y()+")="+r.area()+"<BR>");
</script>

Times Viewed: 0

Leave a Reply

Your email address will not be published. Required fields are marked *