HTML and CSS Reference
In-Depth Information
Figure 8.18 Testing objects.
8.5.5 Creating Subclasses and Inheritance
In the previous examples, we used the prototype object to extend properties and methods
for a given class. In the next chapter you will see how to use prototyping to customize
JavaScript's built-in objects such as Date and String .
Now, to demonstrate how inheritance works, we will define a base class called Pet,
which will have its own properties and methods and can create instances via the “new”
operator . Then we will use this base class to create two additional subclasses called Cat
and Dog. Each of these subclasses (derived classes) will use the prototype property to
inherit the properties and methods of the Pet class (see Figure 8.19). Both the Cat and
the Dog class will be customized to have their own speak() method. Even though the
name of the method is the same for both the Cat and Dog class, JavaScript will call the
speak() method for the object to which it belongs; that is, when the speak() method is
called for a Cat object, it will return “Meow”, and when called for a Dog object, it will
say “Woof”. See Example 8.15 for the program code.
Object
Pet
Cat
Dog
Figure 8.19 A hierarchical tree-like structure used to describe base class and
derived classes.
 
 
Search WWH ::




Custom Search