Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

Lesson 1: Creating JavaScript objects CHAPTER 6 275


This test is successful, so replace the getInfo method and add more tests. The following
test code does this.
test("Instance Test Using Prototype and getters", function () {
expect(4);
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);
Vehicle.prototype.getInfo = function () {
return 'Car Year: ' + this.getYear()
+ ' Make: ' + this.getMake()
+ ' Model: ' + this.getModel();
};
var expected = 'Car Year: 2000 Make: Ford Model: Fusion';
var actual = car1.getInfo();
equal(actual, expected, 'Expected value: ' + expected +
' Actual value: ' + actual);
var expected = 'Car Year: 2010 Make: BMW Model: Z4';
var actual = car2.getInfo();
equal(actual, expected, 'Expected value: ' + expected +
' Actual value: ' + actual);
});

The test result is shown in Figure 6-7. You can replace the getInfo method and, because
the data is exposed as read-only, it’s available to be used in the new method. In addition, the
privileged getters are small, which minimizes the amount of memory consumed when each
instance has a copy of the method. Remember to create only getter methods as needed and
to keep them small and concise.

Quick check
■■How can you expose private data as read-only?

Quick check answer
■■Add a getter method that retrieves the data but cannot change the data.
Free download pdf