↑
Main Page
dynamic prototyping
}
Rectangle.prototype = new Polygon();
Rectangle.prototype.getArea = function () {
return this.length * this.width;
};
Notice that the
Rectangle
constructor also doesn’t accept
sides
as an argument, and once again a con-
stant value (
4
) is passed directly to the
Polygon
constructor. Also similar to
Triangle
,
Rectangle
introduces two new properties as arguments to the constructor and then overrides the
getArea()
method.
Testing the code
You can test the code created for this example by running the following code:
var triangle = new Triangle(12, 4);
var rectangle = new Rectangle(22, 10);
alert(triangle.sides); //outputs “3”
alert(triangle.getArea()); //outputs “24”
alert(rectangle.sides); //outputs “4”
alert(rectangle.getArea()); //outputs “220”
This code creates a triangle, with a base of
12
and a height of
4
, and a rectangle, with a length of
22
and
a width of
10
. Then, both the number of sides and the area of each shape are output to prove that the
sides
property is being properly filled and the
getArea()
method is returning the correct value. The
area of the triangle should be
24
and the area of the rectangle should be
220
.
What about dynamic prototyping?
The previous example uses the hybrid constructor/prototype paradigm of object definition to show
inheritance, but does it work with dynamic prototyping? The answer is no.
The reason that inheritance doesn’t work with dynamic prototyping is because of the unique nature of
the
prototype
object. Take a look at the following code (which is incorrect, but important to study
nonetheless):
function Polygon(iSides) {
this.sides = iSides;
if (typeof Polygon._initialized == “undefined”) {
Polygon.prototype.getArea = function () {
return 0;
};
Polygon._initialized = true;
}
}
function Triangle(iBase, iHeight) {
114
Chapter 4
07_579088 ch04.qxd 3/28/05 11:36 AM Page 114
Free JavaScript Editor
Ajax Editor
©
→