New book: Training Guide: Programming in HTML5 with JavaScript and CSS3

674387.inddWe are delighted to announce that Training Guide: Programming in HTML5 with JavaScript and CSS3 (ISBN 9780735674387), by Glenn Johnson, is now available for purchase!

Designed to help experienced programmers develop real-world, job-role-specific skills—this Training Guide focuses on creating applications with HTML5, JavaScript, and CSS3. Build hands-on expertise through a series of lessons, exercises, and suggested practices—and help maximize your performance on the job.

  • Provides in-depth, hands-on training you take at your own pace:

    - Focuses on job-role-specific expertise for using HTML5, JavaScript, and CSS3 to begin building modern web and Windows 8 apps

  • - Features pragmatic lessons, exercises, and practices

  • - Creates a foundation of skills which, along with on-the-job experience, can be measured by Microsoft Certification exams such as 70-480

  • - Coverage includes: creating HTML5 documents; implementing styles with CSS3; JavaScript in depth; using Microsoft developer tools; AJAX; multimedia support; drawing with Canvas and SVG; drag and drop functionality; location-aware apps; web storage; offline apps; writing your first simple Windows 8 apps; and other key topics

Order this book from The Microsoft Press Store, Amazon, Barnes & Noble, or an independent bookstore.

The book’s Contents at a Glance and an excerpt from the Introduction can be found in this previous post. Today’s post features an excerpt from Chapter 6, “Essential JavaScript and jQuery.”

Chapter 6
Essential JavaScript and jQuery

The flexibility of JavaScript is amazing. In the previous chapters, you learned how to add JavaScript code to your webpage to provide dynamic changes to the page when an event is triggered.

One of the biggest difficulties with webpage development is the differences among different browsers, but this book is primarily focused on HTML5, CSS3, and JavaScript (ECMAScript5.1). A completely separate book could be written that deals just with the differences among browsers and browser versions.

In this chapter, you learn how to create objects, which are an important aspect of JavaScript. You use objects to create entities, which are passed to and from the server, and to encapsulate functionality that you want to modularize. You also need to extend objects that others have created.

This chapter also introduces jQuery, the answer to writing browser-compatible code. Although jQuery doesn’t solve all browser-compatibility issues, it does solve most of the day-to-day issues that you encounter among browsers. In addition, jQuery is fun and easy to use.

Lessons in this chapter:
    ■ Lesson 1: Creating JavaScript objects
    ■ Lesson 2: Working with jQuery

Before you begin

To complete this book, you must have some understanding of web development. This chapter requires the hardware and software listed in the “System requirements” section in the book’s Introduction.

Lesson 1: Creating JavaScript objects

In JavaScript, everything is an object. Strings, numbers, and functions are all objects. You have learned how to create functions, so you already have exposure to creating objects, as you see in this lesson.

After this lesson, you will be able to:
     ■ Understand basic HTTP protocol actions.
     ■ Understand how data is sent to the server.
Estimated lesson time: 20 minutes

Using object-oriented terminology

In many object-oriented languages, when you want to create objects, you start by creating a class, which is a blueprint for an object. Like a blueprint for a house, the blueprint isn’t the house; it’s the instructions that define the type of object that you will be constructing, which is the house. By using a house blueprint, you can create, or construct, many houses that are based on the blueprint. Each house is an object of type house, also known as an instance of the house type.

The developer writes the class, which is then used to construct objects. In a baseball application, you might create a Player (classes are normally capitalized) class that has properties for first and last name, batting average, error count, and so on. When you create your team, you might use the Player class to create nine Player objects, each having its own properties. Each time you construct a Player object, memory is allocated to hold the data for the player, and each piece of data is a property, which has a name and a value.

The three pillars of object-oriented programming are encapsulation, inheritance, and polymorphism. Encapsulation means that you hide all details except those that are required to communicate with your object in order to simplify the object for anyone using the object. Inheritance means that you can create an “is a” relationship between two classes, in which the child class automatically inherits everything that is in the parent class. Polymorphism means that you can execute a function on the parent class, but the behavior changes (morphs) because your child class has a function that overrides the function in the parent class.

The parent class is also known as the base class, the super class, or the generalized class. The child class is also known as the derived class, the subclass, or the specialized class. Because it’s easy to think of actual children inheriting from parents, the terms parent and child are usually used, but you should remember the other terms for these classes to communicate effectively with others about object-oriented programming.

In object-oriented programming, objects can have data implemented as properties and behaviors implemented as methods. A property is essentially a variable that is defined on an object and owned by the object. A method is a function that is defined on an object and owned by the object.

Understanding the JavaScript object-oriented caveat

JavaScript is a very flexible language. You can create objects, but the relationship between the JavaScript language and class-based, object-oriented programming is not direct. The most glaring example is that there is no class keyword in JavaScript. If you’re familiar with class-based, object-oriented programming, you’ll be struggling to find the “class.”

JavaScript is a prototype-based, object-oriented programming language. In JavaScript, everything is an object, and you either create a new object from nothing, or you create an object from a clone of an existing object, known as a prototype.

Conceptually, you can simulate class creation by using a function. Class-based, object-oriented purists dislike the idea of a function being used to simulate a class. Keep an open mind as patterns are presented. This lesson should give you what you need to accomplish your tasks.

The problem you typically encounter is finding one correct solution for all scenarios. As you read on, you’ll find that achieving proper encapsulation of private data requires you to create copies of the functions that can access the private data for each object instance, which consumes memory. If you don’t want to create copies of the method for each object instance, the data needs to be publicly exposed, thus losing the benefits of encapsulation, by which you hide object details that users shouldn’t need to see.

The general consensus of this issue of encapsulation versus wasteful memory consumption is that most people would rather expose the data to minimize memory consumption. Try to understand the benefits and drawbacks of each pattern when deciding which option to implement in your scenario.

Using the JavaScript object literal pattern

Probably the simplest way to create an object in JavaScript is to use the object literal syntax. This starts with a set of curly braces to indicate an object. Inside the curly braces is a comma-separated list of name/value pairs to define each property. Object literals create an object from nothing, so these objects contain precisely what you assign to them and nothing more. No prototype object is associated with the created object. The following example demonstrates the creation of two objects that represent vehicles.

var car1 = {
year: 2000,
make: 'Ford',
model: 'Fusion',
getInfo: function () {
return 'Vehicle: ' + this.year + ' ' + this.make + ' ' + this.model;
}
};

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 getInfo 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.

Creating dynamic objects by using the factory pattern

In addition to using the JavaScript literal object syntax, JavaScript has an Object type, and you can use it to create an object programmatically. Object has a prototype object that is cloned when you use the new keyword to create a new Object instance. The prototype object has the following inherited methods.

constructor   The function that is called to initialize a new object
hasOwnProperty   Returns a Boolean indicator of whether the current object has the specified property
isPrototypeOf   Returns a Boolean indicator of whether the current object is in the specified object’s prototype object chain
propertyIsEnumerable   Returns true if the object can be enumerated in a for...in loop
toLocalString   Converts a date to a string value based on the current local
toString   Returns the string representation of the current object
valueOf   Returns the value of the current object converted to its most meaningful primitive value

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 demonstrates 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 structure 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.