Training Guide: Programming in HTML5 with JavaScript and CSS3 Ebook

(Nora) #1

264 CHAPTER 6 Essential JavaScript and jQuery


var car2 = {
year: 2010,
make: 'BMW',
model: 'Z4',
getInfo: function () {
return 'Vehicle: ' + this.year + ' ' + this.make + ' ' + this.model;
}
};
In this example, public properties are created for year, make, model, and getInfo. The get-
Info property doesn’t contain data; it references an anonymous function instead, so getInfo
is a method. The method uses the this keyword to access the data. Remember that the this
keyword references the object that owns the code where the this keyword is. In this case, the
object is being created. If the this keyword were omitted, the code would look in the global
namespace for year, make, and model.
To test this code, the following QUnit test checks to see whether each object contains the
data that is expected.
test("Object Literal Test", function () {
expect(2);
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 test performs an assertion by using the car1 variable and then performs another
assertion by using the car2 variable. The successful test is shown in Figure 6-1.
If you want to define an array of items and assign it to a property, you can use square
brackets as shown in the following example.
var car1 = {
year: 2000,
make: 'Ford',
model: 'Fusion',
repairs: ['repair1', 'repair2', 'repair3'],
getInfo: function () {
return 'Vehicle: ' + this.year + ' ' + this.make + ' ' + this.model;
}
};
Because this is one of the easiest ways to create an object, you’ll probably use it to gather
data to send to other code. In this example, two instances of a type Object are created, and
properties are dynamically added to each instance. This does not create a Vehicle type.
Free download pdf