↑
Main Page
UML
In UML, you never duplicate properties or methods that are inherited unless a method is being overrid-
den (or overloaded, which is not possible in ECMAScript).
The code for the
Triangle
class is:
function Triangle(iBase, iHeight) {
Polygon.call(this, 3);
this.base = iBase;
this.height = iHeight;
}
Triangle.prototype = new Polygon();
Triangle.prototype.getArea = function () {
return 0.5 * this.base * this.height;
};
Note that the
Triangle
constructor accepts two arguments,
base
and
height
, even though the
Polygon
constructor accepts just one,
sides
. This is because you already know the number of sides in a triangle,
and you don’t want to allow the developer to change that. So, when you use object masquerading, the
number
3
is passed to the
Polygon
constructor as the number of sides for this object. Then, the values for
base
and
height
are assigned the appropriate properties.
After using prototype chaining to inherit the methods,
Triangle
then overrides the
getArea()
method
to provide the custom calculation required for the calculation of triangle areas.
The last class is
Rectangle
, which also inherits from
Polygon
. Rectangles have four sides and the area
is calculated by multiplying the length by the width, which are two properties needed for the class.
Rectangle
fits into the earlier UML diagram next to
Triangle
because both have
Polygon
as a super-
class (see Figure 4-6).
Figure 4-6
The ECMAScript code for
Rectangle
is as follows:
function Rectangle(iLength, iWidth) {
Polygon.call(this, 4);
this.length = iLength;
this.width = iWidth;
Triangle
base : integer
height: integer
getArea(): integer
Polygon
sides : integer
getArea(): integer
Rectangle
length : integer
width : integer
getArea(): integer
113
Inheritance
07_579088 ch04.qxd 3/28/05 11:36 AM Page 113
Free JavaScript Editor
Ajax Editor
©
→