Game Development Reference
In-Depth Information
What happens here is that the Vehicle constructor is called, using the same object that is created
when the Car constructor is invoked. In essence, you're telling the interpreter that the Car object
( this ) you're currently manipulating is actually also a Vehicle object . So you can see the two
important aspects of inheritance:
Car object is also a Vehicle ).
A class that inherits from another class copies its functionality (
There is a relationship between objects (a
Car objects have
the same member variables, properties, and methods as Vehicle objects).
Because Car inherits from Vehicle , you also say that Car is a subclass or derived class of Vehicle ,
or that Vehicle is the superclass , or parent class , or base class , of Car . The inheritance relationship
between classes is widely used; and in a good class design, it can be interpreted as “is a kind of.”
In this example, the relationship is clear: a car is a kind of vehicle. The other way around isn't always
true. A vehicle isn't always a car. There could be other subclasses of Vehicle , for example:
function Motorbike(brand) {
Vehicle.call(this);
this.numberOfWheels = 2;
this.brand = brand;
this.cylinders = 4;
}
Motorbike.prototype = Object.create(Vehicle.prototype);
A motorbike is also a kind of vehicle. The Motorbike class inherits from Vehicle and adds its own
custom member variable to indicate the number of cylinders. Figure 11-1 illustrates the hierarchy of
classes. For a more expanded version of this hierarchy, see Figure 11-4 .
Vehicle
Car
Motorbike
Figure 11-1. Inheritance diagram of Vehicle and its subclasses
Game Objects and Inheritance
The “is a kind of” relationship also holds for the game objects in the Painter game. A ball is a kind of
game object, and so are the paint cans and the cannon. You can make this inheritance relationship
explicit in the program by defining a generic class called ThreeColorGameObject and having your
actual game-object classes inherit from that generic class. You can then put everything that defines
what a three-color game object is in that class, and the ball, the cannon, and the paint can will be
special versions of that class.
 
Search WWH ::




Custom Search