In addition to setting properties, constructors can also define methods. This way, as soon as the object is created it will have its own methods as well.
Here we have a Rectangle constructor, which sets the height and width properties equal to the arguments, just like our Person did with name and age.
Notice we have added a calcArea method. This calculates the area of the rectangle in terms of its height and width.
Line 11 creates a new object rex which makes use of the constructor. You can see how rex calls the calcArea method in line 12and saves the result in a variable, area.
Instructions
Define a new method on line 8,
calcPerimeter
, which calculates and returns the perimeter for a Rectangle in terms ofheight
and width
.
function Rectangle(height, width) {
this.height = height;
this.width = width;
this.calcArea = function() {
return this.height * this.width;
};
this.calcPerimeter = function() {
return 2*this.height + 2*this.width
};
}
var rex = new Rectangle(7,3);
var area = rex.calcArea();
var perimeter = rex.calcPerimeter();
No comments:
Post a Comment