Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

280 CHAPTER 6 Essential JavaScript and jQuery


which accepts a parameter for the this object, and parameters for the parameters on the
function being called, as follows.
var Car = (function (parent) {
function Car(year, make, model) {
parent.call(this, year, make, model);
this.wheelQuantity = 4;
}
return Car;
})(Vehicle);

Notice how this example used the call method to modify the this object; the this object is
the Car object, so the call to the parent constructor function creates year, make, and model
on the Car object. The Function object has another method, apply, that does the same thing,
but the extra parameters are passed as an array instead of as a comma-delimited list.
Next, the inheritance must be set up. You might think that you’ve already set up inheri-
tance because the previous example calls the parent class’s constructor, and the year, make,
and model are created on Car, but getInfo and startEngine were not inherited. The inheri-
tance is accomplished by changing the Car prototype object to be a new Vehicle object.
Remember that the prototype is the object that is cloned to create the new object. By default,
the prototype is of type Object. After the new Vehicle is assigned to the prototype, the con-
structor of that Vehicle is changed to be the Car constructor as follows.
var Car = (function (parent) {
Car.prototype = new Vehicle();
Car.prototype.constructor = Car;
function Car(year, make, model) {
parent.call(this, year, make, model);
this.wheelQuantity = 4;
}
return Car;
})(Vehicle);

Finally, you can add more methods into Car. In this example, the getInfo method is added,
which replaces the Vehicle getInfo method. The new getInfo gets some code reuse by calling
the existing getInfo method on the parent Vehicle object’s prototype. However, you must use
the call method and pass the this object as follows.
var Car = (function (parent) {
Car.prototype = new Vehicle();
Car.prototype.constructor = Car;
function Car(year, make, model) {
parent.call(this, year, make, model);
this.wheelQuantity = 4;
}
Car.prototype.getInfo = function () {
return 'Vehicle Type: Car ' + parent.prototype.getInfo.call(this);
};
return Car;
})(Vehicle);
Free download pdf