Game Development Reference
In-Depth Information
Inheritance
Using prototypes in JavaScript, it's possible to group these similarities together in a sort of generic
class and then define other classes that are a special version of this generic class. In object-oriented
jargon, this is called inheritance , and it's a very powerful language feature. In JavaScript, inheritance
is made possible by the prototype mechanism. Consider the following example:
function Vehicle() {
this.numberOfWheels = 4;
this.brand = "";
}
Vehicle.prototype.what = function() {
return "nrOfWheels = " + this.numberOfWheels + ", brand = " + this.brand;
};
Here you have a very simple example of a class for representing vehicles (you can imagine that
this could be useful for a traffic-simulation game). To keep things simple, a vehicle is defined by
a number of wheels and a brand. The Vehicle class also has a method called what that returns a
description of the vehicle. This could be useful if you wanted to create a website that presented a list
of vehicles in a table. You can use this class as follows:
var v = new Vehicle();
v.brand = "volkswagen";
console.log(v.what()); // outputs "nrOfWheels = 4, brand = volkswagen"
There are different types of vehicles, such as cars, bikes, motorbikes, and so on. For some of these
types, you would like to store additional information. For example, for a car, it could be useful to
store whether it's a convertible; for the motorbike, how many cylinders it has; and so on. You can
use the prototype-based inheritance mechanism in JavaScript to do that. Here is an example of a
class called Car :
function Car(brand) {
Vehicle.call(this);
this.brand = brand;
this.convertible = false;
}
Car.prototype = Object.create(Vehicle.prototype);
There are a couple of new things in this class declaration. At the bottom, you assign a value to the
prototype object of Car . You do this by using the Object.create method. In this case, you make a
copy of the prototype object of Vehicle , and you store that copy in the prototype object of Car .
In other words, Car now has the same functionality as Vehicle , including the what method:
var c = new Car("mercedes");
console.log(c.what()); // outputs "nrOfWheels = 4, brand = mercedes"
In the constructor of Car is the following line:
Vehicle.call(this);
 
Search WWH ::




Custom Search