Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

274 CHAPTER 6 Essential JavaScript and jQuery


replace individual instance functions and you don’t mind making your data public, the proto-
type is efficient.

Quick check
■■You want to add a method to all instances of Vehicle. How do you do this?

Quick check answer
■■Add the method by using the Vehicle object’s prototype method.

Debating the prototype/private compromise


You’ve learned the primary patterns for creating a JavaScript object, but there can be a com-
promise in which you can have private data that is readable by creating a method for retriev-
ing the data, also known as a getter, which has no setter, a method for setting the value. This
would require you to write a function that is copied for each object, but you should keep the
function as small as possible, as shown in the following code example.
function Vehicle(theYear, theMake, theModel) {
var year = theYear;
var make = theMake;
var model = theModel;
this.getYear = function () { return year; };
this.getMake = function () { return make; };
this.getModel = function () { return model; };
}
Vehicle.prototype.getInfo = function () {
return 'Vehicle: ' + this.getYear() +
' ' + this.getMake() +
' ' + this.getModel();
}

The QUnit test for this code creates two instances of Vehicle and, for each assertion,
executes the getInfo method of each object and checks for the proper value. The test is as
follows.
test("Instance Test Using Prototype and getters", function () {
expect(2);
var car1 = new Vehicle(2000, 'Ford', 'Fusion');
var car2 = new Vehicle(2010, 'BMW', 'Z4');
var expected = 'Vehicle: 2000 Ford Fusion';
var actual = car1.getInfo();
equal(actual, expected, 'Expected value: ' + expected +
' Actual value: ' + actual);
var expected = 'Vehicle: 2010 BMW Z4';
var actual = car2.getInfo();
equal(actual, expected, 'Expected value: ' + expected +
' Actual value: ' + actual);
});
Free download pdf