Lesson 1: Creating JavaScript objects CHAPTER 6 267
make = theMake;
model = theModel;
getInfo = function () {
return 'Vehicle: ' + year + ' ' + make + ' ' + model;
};
}
There are several problems with this code. All the variables are defined without the var
keyword, so year, make, model, and getInfo are automatically defined in the global scope and
are accessible from anywhere. The following is a passing QUnit test that initializes Vehicle and
calls the getInfo method to retrieve the data.
test("Function Test", function () {
expect(2);
Vehicle(2000, 'Ford', 'Fusion');
var expected = 'Vehicle: 2000 Ford Fusion';
var actual = getInfo();
equal(actual, expected, 'Expected value: ' + expected +
' Actual value: ' + actual);
expected = 2000;
actual = year;
equal(actual, expected, 'Expected value: ' + expected +
' Actual value: ' + actual);
});
The Vehicle function accepts three parameters and doesn’t return anything. Instead, it is
setting global variables, and there is no provision for multiple instances. To prove that global
variables are being set, the second assertion is checking to see whether there is a global vari-
able named year that equals 2,000. This assertion succeeds, which proves that the data is not
encapsulated, and there is only one copy of the data. For example, the following QUnit test
fails.
test("Failing Function Test", function () {
expect(1);
Vehicle(2000, 'Ford', 'Fusion');
Vehicle(2010, 'BMW', 'Z4');
var expected = 'Vehicle: 2000 Ford Fusion';
var actual = getInfo();
equal(actual, expected, 'Expected value: ' + expected +
' Actual value: ' + actual);
expected = 2000;
actual = year;
equal(actual, expected, 'Expected value: ' + expected +
' Actual value: ' + actual);
});
Figure 6-2 shows the failures. The problem is that year, make, and model of the second
vehicle replaced year, make, and model of the first vehicle. The variable getInfo was also
replaced, but instead of holding data, it holds a reference to the function code. The getInfo
variable’s value was replaced with new function code; it just happened to be the same code.
Once again, there is no encapsulation.