Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 1: Creating JavaScript objects CHAPTER 6 279


Vehicle.prototype.getInfo = function () {
return this.year + ' ' + this.make + ' ' + this.model;
};
Vehicle.prototype.startEngine = function () {
return 'Vroom';
};
return Vehicle;
})();
This class is wrapped in an IIFE. The wrapper encapsulates the function and the Vehicle
prototype. There is no attempt to make the data private. The code works as follows.
■■When the code is loaded into the browser, the IIFE is immediately invoked.
■■A nested function called Vehicle is defined in the IIFE.
■■The Vehicle function’s prototype defines getInfo and startEngine functions that are on
every instance of Vehicle.
■■A reference to the Vehicle function is returned, which is assigned to the Vehicle
variable.
This is a great way to create a class, and all future class examples use this pattern. To create
Vehicle objects, you use the new keyword with the Vehicle variable. The following test creates
an instance of Vehicle and tests the getInfo and startEngine methods.
test('Vehicle Inheritance Test', function () {
expect(2);
var v = new Vehicle(2012, 'Toyota', 'Rav4');
var actual = v.getInfo();
var expected = '2012 Toyota Rav4';
equal(actual, expected, 'Expected value: ' + expected +
' Actual value: ' + actual);
var actual = v.startEngine();
var expected = 'Vroom';
equal(actual, expected, 'Expected value: ' + expected +
' Actual value: ' + actual);
});
Now that you have a Vehicle parent class with three properties and two methods, you can
create child classes for Car and Boat that inherit from Vehicle. Start by writing an IIFE but, this
time, pass Vehicle into the IIFE as follows.
var Car = (function (parent) {

})(Vehicle);

Because Vehicle in this example is the Vehicle variable, not the Vehicle function, Car needs
to be defined after Vehicle. Vehicle is passed into the IIFE and is available inside the IIFE as
parent. Next, the function for Car can be added inside the IIFE. Inside the function, add any
additional properties, such as wheelQuantity, and initialize to four. In the function, call the
parent class’s constructor for Car to allocate memory slots for the year, make, and model.
To call the parent constructor function, use a call method that exists on the Function object,
Free download pdf