Lesson 1: Creating JavaScript objects CHAPTER 6 273
Now that you have a functioning class, change the prototype to see whether it can be
changed across all instances.
test("Instance Test Using Prototype Replace Function", function () {
expect(2);
var car1 = new Vehicle(2000, 'Ford', 'Fusion');
var car2 = new Vehicle(2010, 'BMW', 'Z4');
Vehicle.prototype.getInfo = function () {
return 'Car: ' + this.year + ' ' + this.make + ' ' + this.model;
}
var expected = 'Car: 2000 Ford Fusion';
var actual = car1.getInfo();
equal(actual, expected, 'Expected value: ' + expected +
' Actual value: ' + actual);
var expected = 'Car: 2010 BMW Z4';
var actual = car2.getInfo();
equal(actual, expected, 'Expected value: ' + expected +
' Actual value: ' + actual);
});
This test creates two Vehicle instances and then changes getInfo. Next, the two assertions
are modified to check both instances to see whether they are using the updated getInfo. The
result is shown in Figure 6-6.
FIGURE 6-6 he modification of the getInfo prototype affected all instancesT
You might use the prototype property when creating functions that will be shared across
all instances, but remember that the prototype is defined externally to the constructor
function, so all properties must be public when using the this keyword. If you don’t need to