Main Page

Creating the base class

ClassA.call(this, sColor);
this.name = sName;
}
ClassB.prototype = new ClassA();
ClassB.prototype.sayName = function () {
alert(this.name);
};
In this example, inheritance is accomplished with the two highlighted lines. First, in the
ClassB
con-
structor, object masquerading is used to inherit the
color
property from
ClassA
. In the second high-
lighted line, prototype chaining is used to inherit the methods of
ClassA
. Because this hybrid method
uses prototype chaining, the
instanceof
operator still works correctly.
The following example tests this code:
var objA = new ClassA(“red”);
var objB = new ClassB(“blue”, “Nicholas”);
objA.sayColor(); //outputs “red”
objB.sayColor(); //outputs “blue”
objB.sayName(); //outputs “Nicholas”
A more practical example
In real Web sites and applications, chances are you won’t be creating classes named
ClassA
and
ClassB
.
It’s far more likely that you will create classes that represent specific things, such as shapes. If you con-
sider the shapes example from the beginning of the chapter, the
Polygon
,
Triangle
, and
Rectangle
classes form a nice set of data to explore.
Creating the base class
Think of the
Polygon
class first. What sort of properties and methods are necessary? First, it’s important
to know the number of sides the polygon has, so an integer property named
sides
should be included.
What else might be necessary for a polygon? You may want to determine the area of polygon, so add a
method named
getArea()
to calculate it. Figure 4-3 shows the UML representation of this class.
Figure 4-3
In UML, properties are represented by the property name and type in the section immediately under the
class name. Methods are located under the properties, indicating the method name and the type of the
return value.
Polygon
sides : integer
getArea(): integer
111
Inheritance
07_579088 ch04.qxd 3/28/05 11:36 AM Page 111


JavaScript EditorFree JavaScript Editor     Ajax Editor


©