266 CHAPTER 6 Essential JavaScript and jQuery
After the object is created, you can dynamically add properties to it that hold the data and
reference functions. You can wrap this code in a function that returns the object as shown in
the following code example.
function getVehicle(theYear, theMake, theModel) {
var vehicle = new Object();
vehicle.year = theYear;
vehicle.make = theMake;
vehicle.model = theModel;
vehicle.getInfo = function () {
return 'Vehicle: ' + this.year + ' ' + this.make + ' ' + this.model;
};
return vehicle;
}
This code takes advantage of JavaScript’s dynamic nature to add year, make, model, and
getInfo to the object and then returns the object. Placing this code in a function makes it easy
to call the getVehicle function to get a new object. The encapsulation of the code to create an
object is commonly referred to as using the factory pattern. Can you create multiple instances
of vehicle? You can create multiple instances of Object and add properties dynamically to
each instance, but the actual type is Object, not vehicle. The following QUnit test demon-
strates the creation of multiple instances.
test("Create Instances Test Using Factory Pattern", function () {
expect(2);
var car1 = getVehicle(2000, 'Ford', 'Fusion');
var car2 = getVehicle(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);
});
This might be all you need when you are gathering some data to put into an object struc-
ture and pass to some other code or service. Although the getVehicle function encapsulates
the object creation, the properties are all public. This can be desirable in some scenarios, but
if you want the data to be private, this approach won’t work. Like when using the literal object
syntax, you might encounter the problem that every vehicle’s type is Object, and you might
want to create a Vehicle class to have a named Vehicle type.
Creating a class
There is no class keyword in JavaScript, but you can simulate a class by starting with a func-
tion, which is actually the constructor function of the object. Consider the following function.
function Vehicle(theYear, theMake, theModel) {
year = theYear;
Key
Te rms