Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

268 CHAPTER 6 Essential JavaScript and jQuery


FIGURE 6-2 he failing test assertions after a second vehicle is usedT

To solve the problem, you want to implement encapsulation. Then you need to create
objects, each with its own data. To implement encapsulation, use the var keyword for the
year, make, and model. This will make these variables private to the function. Notice that the
var keyword is not used with getInfo because the getInfo variable needs to be public to be
called from outside the object, but you don’t want the getInfo variable to be global. Assign
getInfo to the current object by using the this keyword. The result is a class that encapsulates
the data and exposes getInfo to retrieve the data in a controlled way as follows.
function Vehicle(theYear, theMake, theModel) {
var year = theYear;
var make = theMake;
var model = theModel;
this.getInfo = function () {
return 'Vehicle: ' + year + ' ' + make + ' ' + model;
};
}

IMPORTANT PRIVATE DATA ISN’T SECURE
In object-oriented programming, private data is not intended to be secure. Private data
provides encapsulation so the details can be hidden; the user sees only what is necessary
and isn’t bogged down in the details.
Free download pdf