Previous Page TOC Next Page See Page



- 3 -
JavaScript and Object-Oriented Programming


To effectively use JavaScript, it's important to understand the underlying concepts of object-oriented programming and how it relates to JavaScript.

Although JavaScript is object-based, it doesn't offer the full power of object-oriented languages, such as Java and C++. Still, without understanding objects, properties, and methods and how they all work, it isn't possible to leverage all the potential of JavaScript.

This understanding of objects and how they work is especially important for programmers who have no previous experience with object-oriented languages and have used only procedural programming languages, such as C and Pascal.

This chapter briefly examines object-oriented programming and then moves on to look at the following:


Object-Oriented Programming


Describing objects, as used in programming, requires an analogy. In her popular book, Teach Yourself Java, well-known Web author Laura Lemay uses Lego pieces as an example. These small plastic building blocks—which take many different shapes and sizes—can be put together to create any number of different objects, from a car to an airplane to a city.

These individual pieces are objects, and the combined result is an application or a program. By piecing together many objects, a complete program is built. Each object is self-contained; it has a specific role to play and pre-defined ways of talking to other objects.

Beyond this example, another analogy can be used to describe objects themselves. Individual objects are made up of related information and methods for dealing with that information. For example, A car has many pieces of information, including its year of manufacture, its manufacturer, its model, its color, and its owner. This information can be used to print a specification of the car, to change its owner, or to paint it a new color, to name a few.

In object-oriented programming terms, these pieces of data are known as properties of an object; the different actions you can take based on that data are called methods.

For instance, the car object could have the following properties:

It could also have these methods:


Classes


The car object just defined is really more of a template for multiple objects with similar properties and methods, which are collectively called a class. A class defines all the properties and methods of a particular set of objects.

Rather than defining individual objects, object-oriented programming works by defining classes, or abstract models, for the different objects a program needs to work with.

Instances


Once a class has been defined for a general category of objects, you need to create specific instances of it for each particular case to which the object applies. For instance, you could take the car class defined earlier and create instances of it for Joe's red 1990 Ford Mustang and Sue's green 1994 Honda Accord. The year property of the first instance would be 1990, and the color property of the second instance would be green.

Each of these would be an instance of the car class. This instance is an actual object, and although the class is general, the instance is a specific concrete representation of the class.

Inheritance


Classes are grouped together into hierarchies, which makes it possible for classes to inherit properties and methods from an existing class and then add or change properties and methods for a specific purpose. This is called inheritance—when a new class inherits the properties and methods of an existing class.

As an example, you could create a new class called foreignCar that's a subclass (one layer lower in the hierarchy) of the car class defined earlier. This new class will inherit all the properties and methods of the car class, but you could extend it by adding a new property—country— to indicate the country of manufacture and redefining the printInfo method to also print the country of manufacture.

The JavaScript Object Model


With this basic understanding of object-oriented programming, you can see what aspects of it are applied in JavaScript. JavaScript is not a true object-oriented programming language. Instead, it uses objects and instances, but abandons some of the larger, and more complex, mechanisms, such as classes and inheritance. For this reason, JavaScript is often referred to as being object-based rather than object-oriented.

JavaScript offers a compact set of data types, functions, and keywords along with sets of client and server objects that are enough for most scripting needs.

The Navigator Object Hierarchy


The set of built-in objects in client JavaScript offers information about the currently loaded Web page, as well as the environment in which that page exists. These objects are organized in the Navigator Object Hierarchy, which takes the following form:

navigator
window
frame
location
history
document
forms
anchors
links

These objects, and other sub-objects, make up the key objects available in client JavaScript. They are outlined in Table 3.1.

Table 3.1. The Navigator Object Hierarchy.

Object Description
navigator Provides information about the client browser.
window Provides methods and properties for dealing with an actual Navigator Window. Each window is a separate object.
frame Provides properties and methods for dealing with a frame. Each frame is a separate object.
location Provides methods and properties for working with the URL loaded in the window.
history Is used for working with the window's history list.
document Provides properties and methods for working with a document, creating output in the document window and performing other document-related tasks.
forms Provides properties and methods for working with a form and its elements. Each form is a separate form object.
anchors Provides mechanisms for handling anchors. Each anchor is a separate anchor object.
links Provides mechanisms for handling links. Each link is a separate link object.

These objects are available only in client JavaScript. The objects specific to server JavaScript are discussed in Chapter 12, "The LiveWire Object Tree."

Other Objects


In addition to the objects available in the Navigator Object Hierarchy, JavaScript offers some other objects that have more general applications; they are listed in Table 3.2.

Table 3.2. Other JavaScript objects.

Object Description
string Allows programs to work with string data. Each string variable in JavaScript is actually an instance of this object.
Math Provides methods and properties to perform mathematical calculations ranging from trigonometry to square roots.
Date Provides methods and functions for tracking and manipulating dates.

User-Defined Objects


Users can define their own objects and then create instances of them in JavaScript by creating a constructor function. A constructor function defines the properties and methods that make up an object—much as a class does in object-oriented programming. Using a constructor function, you can define multiple instances of the object.

In general, this is the syntax for the constructor function:

function functionName(parameters) {
   Object Definition
}

For example, you could create a simple version of the car object with a single property for the owner and nothing else:

function car() {
   this.owner = "";
}

Here, you define a constructor function for the car object that takes no parameters. In the function, you define a single property called owner and assign an empty string to the property. There are two important points to remember:

In the previous example, you don't pass any parameters to the constructor function or assign an initial value to the owner property (other than the empty string, of course).

To use the object, you need to create an instance of it. For example, you could create an instance called car1 using the new keyword:

var car1 = new car();

Once this is done, you can refer to the owner property as car1.owner and assign a name to it:

car1.owner = "Owner's Name";

Parameters can be passed to the function so that values are assigned to the properties when you instantiate an object. For instance, if you create a name parameter in the constructor definition,

function car(name) {
   this.owner = name;
}

then you can create an instance of the car object and assign a value to the owner property with one command:

var car1 = new car("Owner's Name");

Now that you see how this basic framework operates, you can extend the constructor function to define all the properties of the car object:

function car(name) {
   this.owner = name;
   this.maker = "Does not own a car";
   this.model = "Does not own a car";
   this.color = "Does not own a car";
   this.year = "Does not own a car";
}

Next, you could define a instance of the object for a particular owner; once he or she buys a car, then assign values to the other four properties (other than owner):

var car1 = new car("Owner's name");
car1.maker = "Ford";
car1.model = "Mustang";
car1.color = "red";
car1.year = "1990";

Now you need to add methods to the function. This is a two-step process: first, create a function that defines the method, and second, add the method to the constructor function.

For instance, if you want to define the printInfo method, then create a function that specifies how the method works:

function doPrintInfo() {
   writeln("Owner's Name:" + this.name);
   writeln("Manufacturer:" + this.maker);
   writeln("Model       :" + this.model);
   writeln("Color       :" + this.color);
   writeln("Year:       :" + this.year);
}

Note that this function uses the this keyword again to refer to the particular object the function is associated with.



Note:

This function uses the writeln() method of the document object, which is discussed in more detail in Chapter 4, "General Objects and Functions". The writeln() method allows a script creating HTML output to be displayed in the document window.


The next step is to associate the function as a method of the car object by adding this line to the constructor function for the object:

this.printInfo = doPrintInfo;

This statement indicates that the printInfo method is defined by the doPrintInfo function.

Extending this, you can create the newOwner and rePaint methods by first writing functions to define the methods,

function doNewOwner() {
   this.owner = prompt("Enter the new owner's name:","Name");
}
function doRePaint() {
   this.color = prompt("Enter the new color:","Color");
}

then adding them to the constructor function:

function car(name) {
   this.owner = name;
   this.maker = "Does not own a car";
   this.model = "Does not own a car";
   this.color = "Does not own a car";
   this.year = "Does not own a car";
   this.printInfo = doPrintInfo;
   this.newOwner = doNewOwner;
   this.rePaint = doRePaint;
}

You could then define an instance of the car object, assign values to its properties, and print the information out with the following commands:

var car1 = new car("John");
car1.maker = "Honda";
car1.model = "Accord";
car1.color = "White";
car1.year = "1994";
car1.printInfo();

Those statements would produce text like this:

Owner's Name : John
Manufacturer : Honda
Model        : Accord
Color        : White
Year         : 1994

Objects as Properties of Objects


Beyond assigning simple properties to objects, you can also use objects as properties of another object. For instance, if you were to create an engine object with two properties,

function engine() {
   this.cylinders = 0;
   this.horsepower = 0;
}

you could add it to your definition of the car object:

function car(name) {
   this.owner = name;
   this.maker = "Does not own a car";
   this.model = "Does not own a car";
   this.color = "Does not own a car";
   this.year = "Does not own a car";
   this.printInfo = doPrintInfo;
   this.newOwner = doNewOwner;
   this.rePaint = doRePaint;
   this.engine = new engine();
}

Notice that the property is defined in the same way that an instance of the car object was created earlier by using the new keyword.

Then, if you create an instance of the car object called car1, you could refer to the properties of the engine property as car1.engine.cylinders and car1.engine.horsepower.

Adding Properties to an Object


Once an object has been defined with a constructor function and instances have been created, you might need to extend it by adding properties to either a particular instance or all instances of the object.

Adding a Property to a Specific Object Instance

It's easy to add a property to a specific instance of an object. For example, if you have two instances of the car object—car1 and car2—you could add an accident property to car2 simply by assigning a value to it:

car2.accident = true;

This would not add the property to car1, however, and future instances of the car object also wouldn't have the accident property unless it was explicitly created for them in the same way.

Adding a Property to All Instances of an Object

You can also add a property or method to all instances of an object, as well as future instances of an object, by using the prototype property of all constructor functions. The syntax for this property can be one of the following two:

constructorFunctionName.prototype.newPropertyName = value;

or

constructorFunctionName.prototype.newMethodName = methodDefinitionName;

For instance, if after creating the two car instances in the previous example, you wanted to add an accident property to both instances as well as to the constructor function, then you could use:

car.prototype.accident = false;

This statement would add the properties to all instances of the object and to the constructor and would set the initial value to false. If you then created a new instance called car3, it would automatically include an accident property with a false value.



Note:

The prototype property isn't available in Navigator 2 and works only with Navigator 3. If you need to ensure full compatibility with Navigator 2 users, it's best to avoid this feature of JavaScript.



Arrays in JavaScript


In JavaScript, arrays are actually a type of object; each array entry is, in fact, a property of an instance of the Array object. Arrays are created by creating instances of the Array() constructor function using this form:

var arrayName = new Array();

Individual array elements are referred to with arrayName[index] and all arrays start at index zero.

Array lengths in JavaScript aren't fixed, but can be increased dynamically by simply assigning values to new array entries, in much the same way that you dynamically added properties to an instance of an object earlier in this chapter.

For example, the following lines would create an array named testArray and set its size to 100 elements (from zero to 99) by assigning an empty string to the element with index 99:

var testArray = new Array();
testArray[99] = "";

Next, you could extend the array's length again by assigning a value to an even larger index.

You can also set an initial size for an array by passing the number of elements to the Array() constructor function as an argument:

var testArray = new Array(100);

It's also possible to create an array and assign values to all its initial elements at the time the array is created. This is done by passing the values for the elements to the Array() function as arguments:

var anotherArray = new Array("One element",2,false);

This statement would create a three-element array with the values "One element", 2, and false assigned to the array.



Note:

Unlike some structured programming languages, JavaScript doesn't require all entries in an array to share the same data type. In the previous example, for instance, you created a three-element array of a string, an integer, and a Boolean value, respectively.


Because arrays are objects, they also have some methods and properties:


Summary


In this chapter, you took a close look at objects, the building blocks on which JavaScript is built. Sets of pre-defined objects are what give both client and server JavaScript their capabilities.

Objects define groups of information and methods for working with that information. As a programmer, you can extend JavaScript by creating objects with their own properties and methods.

You also looked at the Navigator Object Hierarchy—that set of objects that makes up the core of client JavaScript—and discussed some other objects found in JavaScript, such as the string and Date objects.

Finally, you learned about arrays and their relationship with the JavaScript object model. As a unique type of object, arrays share many of the features of objects and have a flexibility not found in many other languages.

In the next chapter, you'll move on to explore the main objects and functions of client JavaScript.

Previous Page Page Top TOC Next Page See Page