Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1
Lesson 1: Creating JavaScript objects CHAPTER 6 269

Remember that the this keyword references the object that owns the current code. The
way the test is currently written, the this keyword references the global object, and getInfo
will still be a global variable. To solve the problem, the new keyword must be used to create
an object from this class, as shown in the modified test code.
test("Encapsulation Test", 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);
expected = 2000;
actual = year;
equal(actual, expected, 'Expected value: ' + expected +
' Actual value: ' + actual);
});

Notice that a new variable is defined, car1, and it is assigned the object that is created by
using the new keyword. After that, another new variable is defined, car2, and it is assigned the
second Vehicle object created by using the new keyword. Two instances of the Vehicle class
are being created, which means that two Vehicle objects are being constructed. Each instance
has its own data and its own copy of the getInfo method. The getInfo method is public but
has access to the private data. A method that is public but has access to private data is called
a privileged method.
Figure 6-3 shows the test results. Notice that the first assertion passed, which proves that
there are separate object instances, each having its own data. The second assertion failed. The
failure message states that the year is undefined, which proves that the year is not directly
accessible from the test, which is in the global namespace. Instead, year, in addition to make
and model, is encapsulated in the object.
You have now created a class and constructed objects from the class, but there’s more
to cover in the Vehicle function that is being used as a class. The Vehicle function is known
as a constructor function. The new keyword created an object and executed the constructor
function to initialize the object by creating the year, make, and model private variables and
the public getInfo variable. Each instance has these four variables, and memory is allocated
for them. That’s what you want for the data, but is that what you want for the getInfo variable
that references a function? The answer is that it depends on what you are trying to accom-
plish with your code.

Key
Te rms


Key
Te rms

Free download pdf