JavaScript OO Lite


Let’s turn from OO theory to OO as it’s practiced in JavaScript.

The creator of JavaScript, Brendan Eich, who worked for a company then known as Netscape Communications at the time he gave birth to JavaScript in 1995, has written “JavaScript was born out of a desire to let HTML authors write scripts directly in their documents.”

JavaScript has come to be used in some unanticipated ways—for example, as a server-side scripting language (a programming language processed on a server and not in a client such as a browser) and to create stand-alone programs. But the original primary purpose—and thing the language does best—was to work with objects, and object members, exposed by a document in a Web browser. (JavaScript is also very capable as a scripting language for gluing together applets, or stand-alone programs, created in Java, once again by using the objects and object members exposed by the applets.)

This brings to our attention the two faces of Eve, oops, I mean OO. OO can be used to create objects. But a language such as JavaScript that may not be world class in its ability to create objects (as Java, for example, is) may be very strong in its ability to manipulate objects created by others. This kind of object manipulation, the other face of OO, is extremely important and can be viewed as “OO lite.”

Our discussion of OO and JavaScript will start by showing you how to use object-oriented programming to manipulate HTML documents in a Web browser. You’ve already seen many examples of this presented in an ad-hoc fashion in the earlier chapters of this book, but this chapter presents this material, which you can think of as “client-side OO,” in a more orderly way.

The Dot Operator

We’ve already talked about the dot operator (.), and you’ve seen many examples of its use throughout this book. But let’s talk again explicitly about its role in JavaScript.

In JavaScript, the dot operator is used in three ways. First, it’s the glue that allows you to refer to sub-objects in the object hierarchy. For example:

 window.document 

refers to the document sub-object of the window object.

The JavaScript window object, window, is at the top of the client-side object hierarchy of documents in a browser, as I’ll explain in a little bit. It can be omitted without consequences, so this:

 window.document 

can also be written just as this:

 document 

But when you write document, what you really mean is window.document, and the dot operator is used to glue together a parent object (window) with its child (document). This can get even more hierarchic. For example, the following expression:

 window.document.theForm.theButton 

could be used to refer to an HTML button named theButton, itself part of a form named theForm, in the HTML document currently loaded in the browser.

The dot operator is also used to access object property values. For example, to assign the value of the length property of a String object to a variable, you could use the dot operator as follows:

 var strLen = theString.length; 

Finally, the dot operator is used to invoke object methods. For example, in this book I’ve used the write method of the document object to display text, like so:

 window.document.write("Make it so!"); 

or, more often, abbreviated with the window object implied:

 document.write("I did it my way!"); 

In short, without the dot operator, there would be no way to work with objects in JavaScript!

JavaScript Properties

As you know by now, a property is a setting that describes something about an object. (This is a slightly different way of looking at the fact, which we’ve discussed, that an object property contains data, just like a variable.) Some properties are read-only, meaning you can access the value the property contains but not modify that value. It’s less common but not impossible to have a property that’s write-only, meaning you can set its value but not retrieve the value. Still other properties are read-write, meaning you can set them and retrieve them.

The following is an example of using the read-only length property of the String object that’s built into JavaScript to display the number of characters in the string (spaces do count as characters).

To Read and Display the Length Property:

  1. Use the constructor of the JavaScript String object to create a new variable of type String:

     var theString = new String(); 

  2. Use the window.prompt method to get a string from the user (see Figure 7-2):

     var theString = prompt("Enter a string: ",""); 

    click to expand
    Figure 7-2: The user enters a string in a prompt box.

  3. Use the string.length property of the string to display the number of characters in the string (see Figure 7-3):

     document.write('The string "' + theString +  '" is ' +     theString.length + ' characters long.'); 

    click to expand
    Figure 7-3: The length of the string the user entered is displayed.

See Listing 7-1 for the complete code for displaying the length of a string.

Listing 7.1: Using the String Object’s Length and the Document.Location Properties

start example
 <HTML> <HEAD> <TITLE>Properties</TITLE> </HEAD> <BODY> <H1> <SCRIPT>     var theString = new String();     theString = prompt("Enter a string: ","");     document.write('The string "' + theString +  '" is ' +        theString.length + ' characters long.');     if (window.confirm("Do you want to go to Apress today?"))       window.location = "http://www.apress.com";       </SCRIPT> </H1> </BODY> </HTML> 
end example

The window.location property contains the Uniform Resource Locator (URL) of the current location of the HTML document loaded in the browser. Assigning a URL to the property causes the browser to go to that location. Let’s put this into action to move the current browser to a specific location.

To Set the Location Property (and Move the Browser to a Specific URL):

  1. Use the window.confirm method to allow the user to confirm that they really want to go to the new location (see Figure 7-4):

     window.confirm("Do you want to go to Apress today?") 

    click to expand
    Figure 7-4: The user is asked to confirm the URL.

  2. Embed the confirmation method within a conditional statement that places the new location value in the location property:

     if (window.confirm("Do you want to go to Apress today?"))       window.location = "http://www.apress.com"; 

When the user clicks OK, the browser will open the specified URL (see Figure 7-5). See Listing 7-1 for the complete code for displaying the length of a string.

click to expand
Figure 7-5: The document.location property is set to open the URL.

Note

The confirm method evaluates to true if the user clicks OK and false if the user clicks Cancel.

It’s important to understand that properties, such as location, can be objects in their own right as well as properties. You should also know that there’s an alternative way to reference object properties. You can use the object’s properties array and refer to a specific property by index number or name. Instead of this:

 window.location 

you can write this:

 window["location"] 

Furthermore, you could refer to the location property by index number if you knew the index value for the location property in the window array. We’ll further discuss the issue of the correspondence in JavaScript between arrays and objects later in this chapter.

Methods

Methods operate on or with an object to do something. As you’ve already seen, methods are implemented as functions, and you can pretty much think of them as functions. This means that you can recognize object methods because they’re always followed by parentheses, with or without enclosed parameters.

For example, the window.close() method will close the current browser window. Let’s see how this works!

To Close the Browser Using the window.close() Method:

  1. Use the confirm method to create a condition that checks to make sure the user wants to close the browser window:

     window.confirm("Do you want to close the browser?") 

  2. Create a conditional statement that embeds the confirm condition and invokes the close method if the condition is true:

     if (window.confirm("Do you want to close the browser?"))       window.close(); 

  3. Save the code and open it in a browser. The user will be prompted for confirmation (see Figure 7-6). If the user clicks OK, the browser window will shut. Listing 7-2 shows an HTML page that uses this code to close a window just as it opens.

    Listing 7.2: Using the window.close() Method to Close a Browser Window

    start example
     <HTML> <HEAD> <TITLE>Methods</TITLE> </HEAD> <BODY> <H1>  I'm not even fully opened yet!     <SCRIPT>     if (window.confirm("Do you want to close the browser?"))       window.close();     </SCRIPT> </H1> </BODY> </HTML> 
    end example

    click to expand
    Figure 7-6: The window.close() method is used to close the browser window following a confirmation from the user.

Note

Note that in some browsers, depending on your security settings, you may see a second prompt box, asking if you really want to close the browser.

Caution

For security reasons, some browsers will not allow JavaScript code to close a window it hasn’t opened. If you find that the code shown in Listing 7-2 doesn’t close the window, you’re probably running a browser such as Mozilla that doesn’t allow JavaScript code to shut a window. As an exercise, why not modify the code shown in Listing 7-2 to first open a window and then close it? (This will work because the code is closing a window it has opened.)

Events

In JavaScript, code that handles events fired in an HTML page that’s loaded in the browser is assigned to the event handler function within the HTML element that fires the event. For example, code that responds to a button click event is assigned to the onClick event handler with the HTML <input type=button> form tag that creates the button. (As I’ve mentioned, Chapter 8, “ Understanding Events and Event-Driven Programming,” discusses eventdriven programming in much greater detail.)

Note

Note that the event handler functions for HTML events are case sensitive. The event handler is named onClick, not onclick or Onclick. If you assign code to an onclick event, it will never get fired.

Because we’ve already seen many examples in this book that use an onClick event handler, let’s take a quick look at another event, the onMouseOver event.

Some HTML elements, including links (represented by the <A> tag) and images (denoted by an <IMG> tag), fire an onMouseOver event when the user passes the mouse over a hyperlink.

JavaScript code assigned to the onMouseOver handler function in the tag will be executed when the event is fired.

Let’s take as a really simple example a Web page that just doesn’t want to let go. This is one really codependent piece of HTML!

Joking aside, the actual functionality—or more aptly, dysfunctionality—is to change the URL pointed to by the link when the mouse passes over the link. (As you’d expect from a snippet of dysfunctional code, the URL is changed to something that isn’t a valid destination.) The URL is changed by setting the href property of the link object.

To Change the href Property of a Link in the Link’s onMouseOver Event:

  1. In an HTML document, create a link with a valid HREF attribute:

     <A HREF="http://www.apress.com" > Please do not leave me!</A> 

  2. Within the link tag, add an onMouseOver event handler:

     <A HREF="http://www.apress.com"  onMouseOver= >  Please do not leave me!</A> 

  3. Assign code within quotes to the onMouseOver event that changes the value of the link object’s href property:

     <A HREF="http://www.apress.com"     onMouseOver='this.href="I cannot let you go.";'>     Please do not leave me!</A> 

The code for the codependent link is shown in a codependent HTML page in Listing 7-3. If you open this page in a Web browser and hover the mouse over the hyperlink (as shown in Figure 7-7), the actual URL the link points to changes from a valid Internet destination (http://www.apress.com) to something that can’t be opened in a browser (“I cannot let you go.”), as you can see in the status bar in Figure 7-7.

Listing 7.3: Codependent Link Tag and the onMouseOver Event

start example
 <HTML> <HEAD> <TITLE>onMouseOver Event</TITLE> </HEAD> <BODY> <H1> <A HREF="http://www.apress.com" onMouseOver='this.href="I cannot let you  go.";'>     Please do not leave me!</A> </H1> </BODY> </HTML> 
end example

click to expand
Figure 7-7: The value of the HREF attribute (the URL that the link points to) changes when the onMouseOver event is fired.

Tip

You can put as many JavaScript statements as you’d like in the event handler, provided the statements are separated by semicolons. If you have more than one or two statements, you should put them in a function and simply call the function from the event handler.

The HTML Document Object Hierarchy

HTML documents that are loaded in a Web browser expose an object hierarchy that can be manipulated using JavaScript programs. The objects in this hierarchy are connected to each other by parent-child relationships. This isn’t saying anything more than the child object is accessible as a property of the parent object. For example, you’d use the expression window.document.theForm to reference a form named theForm in a loaded HTML document.

Sibling objects are all properties of the same parent and populate the array of properties of the parent object.

The document object and its children are used to manipulate elements of a document. In contrast, the window object (and some of its children other than the document object) is used to manipulate the window and frame of the document, in other words, the context of the document in the browser.

The first-level “children” of the window object are as follows:

  • navigator: The navigator object contains properties that tell you about the browser in use.

  • frames[ ]: The frames property is an array of references to window objects, one for each HTML frame included in the parent window.

  • location: This is the location object for the window, which stores its URL.

  • history: The history object stores the URLs the browser has visited.

  • document: The document object and its child objects are used to work with the document displayed in a browser window. Children of the document object include HTML forms and controls such as buttons.

Sometimes the objects representing an HTML page exposed to JavaScript can feel like a soap opera with a complex plot (perhaps All My Children starring the document object). Actually, the issues are pretty simple from the developer’s viewpoint: understanding what tools are available in each circumstance.

The Window Object

The window object is the “mother” of all HTML document objects, meaning it’s the parent (or ancestor) of all built-in objects that can be manipulated using client-side JavaScript. As I’ve mentioned before, because the window object is at the top of the hierarchy, it can be referenced implicitly:

 document 

which is the same as writing this:

 window.document 

Similarly, you don’t need to type the following:

 window.onFocus 

because onFocus refers implicitly to the window object. You can just use the expression onFocus.

Essentially, the window object serves two roles:

  • It’s the top of the object hierarchy of a document loaded in a Web browser via the window.document object and its children

  • It’s used to control the browser window and frames (through the frames array).

The JavaScript for/in statement can be used to iterate through the properties array associated with any object, sometimes called the object’s associative array. (Chapter 4, “ Working with Loops,” explained this variant of the for statement for use with objects.)

Advanced Note

JavaScript as a programming language has a Global object that provides properties, provides members, and tracks global variables (those available to all functions in a program). When a JavaScript program is seated on an HTML page and executed in a Web browser, the Global object and the window object are the same thing. (JavaScript programs executing outside a Web browser most likely don’t have a window object, but they do have a Global object.)

The following shows how to use the for/in statement to cycle through and display all the properties of the window object.

To Display All the Properties of the Window Object:

  1. Create the framework for a for/in statement using an index variable to cycle through the object properties:

     for (var i in window) {  } 

  2. Add code that displays each property name (expressed using the index variable, i) and the value of the property (expressed using the properties array of the object, window[i]):

     for (var i in window) {       document.write ("Window property(" + i +  "): " +          window[i] + "<br>");  } 

  3. Save and run the page containing the code (see Listing 7-4). The window object’s properties—and the values of the properties that are primitive JavaScript types—will be displayed as shown in Figure 7-8.

    Listing 7.4: Displaying the Associative Properties Area of a Window Object

    start example
     <HTML> <HEAD> <TITLE>Window Object Properties Array</TITLE> </HEAD> <BODY> <SCRIPT>  for (var i in window) {    document.write ("Window property(" + i +  "): " +       window[i] + "<BR>");  }  </SCRIPT> </BODY> </HTML> 
    end example

    click to expand
    Figure 7-8: The associative array of the properties of the window object is displayed.

Tip

You don’t have any way to know in which order the for/in statement will go through the object’s associative array.

If you look through the properties and values shown in Figure 7-8, you’ll see that many of the values are shown as objects, like this: [option]. This is an opaque and not terrifically useful representation, but at least you know that the property exists in the associative array and that it’s an object as opposed to a primitive type such as a number or text string.

By the way, it’s interesting to watch some of the values shown in Figure 7-8 change. For example, if you move and resize the Web browser, then refresh the document shown in Listing 7-4, both the screenLeft and screenTop values will change (because these represent the current location of the browser window in reference to the screen).

Tip

In Mozilla, as opposed to Internet Explorer, the screenLeft property is known as screenX, and screenTop is screenY.

Displaying an Object’s Associative Array

It’s easy to generalize the code shown in Listing 7-4 and come up with a general function that displays an object’s associative array. Listing 7-5 shows you how you could write this function.

Listing 7.5: A General Function for Displaying an Object’s Associative Array

start example
 function showProperties (theObject){     for (var i in theObject) {        if (theObject[i] != null) {            document.write(i + " : " + theObject[i] + "<br>");        }        else {           document.write(i + "<br>");        }     }     return;  } 
end example

If you place the showProperties function shown in Listing 7-5 in the <HEAD> section of an HTML page and call it with the navigator object as shown in Listing 7-6, you’ll get a display like that shown in Figure 7-9.

Listing 7.6: Displaying the Navigator’s Associative Array

start example
 <HTML> <HEAD> <TITLE>Associative object arrays</TITLE> <SCRIPT>  function showProperties (theObject){     for (i in theObject) {        if (theObject[i] != null) {            document.write(i + " : " + theObject[i] + "<br>");        }        else {           document.write(i + "<br>");        }     }     return;  }  </SCRIPT> </HEAD> <BODY> <SCRIPT>  showProperties(window.navigator);  // showProperties(window.document);  </SCRIPT> </HTML> 
end example

click to expand
Figure 7-9: The navigator object associative array

Tip

The navigator object is important if you’re writing Web applications that must run on different browsers and operating systems. In that case, your code will likely need to inspect the navigator object’s properties and branch conditionally depending on the values of the navigator’s properties.

It’s easy to view the document object’s associative array instead of that belonging to the navigator object. In the code shown in Listing 7-6, simply replace the following statement:

 showProperties(window.navigator); 

with this statement:

 showProperties(window.document); 

When you open the HTML page in a Web browser, the properties of the document object will now be displayed (see Figure 7-10).

click to expand
Figure 7-10: The document object associative array (shown partially)

The showProperties function is written in a general enough way that it can be used to show the contents of the associative properties array of custom objects that you create (in addition to the arrays associated with the objects in the window object hierarchy). I show you how to do this later in this chapter after I show you how to create your own custom objects.

Predefined JavaScript Objects

Now that we’ve had a good look at programming the objects exposed by the document object, let’s have a look at the objects defined within the JavaScript programming language. These are pretty different from the objects exposed to JavaScript when a document is loaded in a Web browser.

JavaScript provides a number of built-in object types. Table 7-1 briefly describes the built-in objects that are standard across most JavaScript implementations. Of course, you’re already familiar with some of them, such as the Array and Number objects. You should also know that, in keeping with its informal style, in JavaScript you create an object simply by using a value of the type of the object—for example, using a number creates a Number object. However, if you prefer, you can explicitly create objects based on the built-in object types using the constructor for the object. For example:

 var theNum = new Number(42); 

Table 7-1: Built-in JavaScript Object Types

Object

Description

Array

Used to work with arrays and to create new Array objects, as explained in Chapter 6, “ Programming with Arrays.”

Boolean

Used to work with Boolean (or logical) objects and to create new Boolean objects.

Date

Manipulates dates and times. Date() can be called as a function without the new operator, in which case it behaves in the same way as a Date object.

Error

Used to work with errors and exceptions and to create new Error objects, as explained in Chapter 10, “ Error Handling and Debugging.”

Function

Used to work with functions and to create new Function objects, as explained in Chapter 5, “ Understanding Functions.”

Global

The Global object contains built-in JavaScript methods and provides a context for global variables (those available to all code in a given application). When JavaScript is being executed in a document in a Web browser, the Global object is the window object described in “ The Window Object ” a little earlier in this chapter.

Math

The Math object contains constants and functions for performing mathematical operations. Note that the Math object can’t be instantiated (another way of saying that you can’t create objects based upon the Math object) and functions as a shared class.

Number

Used to work with numbers and to create new Number objects.

Object

Provides common functionality for all JavaScript objects; see “ The Object Object.”

RegExp

Used to work with, and to create, RegExp, or regular expression objects, which are used to match patterns and are explained in Chapter 9, “ Manipulating Strings.”

String

Used to work with strings and to create new String objects. Working with strings is examined in Chapter 9, “ Manipulating Strings.”

The Object Object

The Object object is the root of all objects in JavaScript.

Put in class terminology, it’s a superclass of all classes in JavaScript. More accurately, because, as we’ve discussed, JavaScript doesn’t really have classes—but rather prototype objects and instance objects—the Object object is the superprototype of all objects in JavaScript. Say that one 10 times quickly!

Do It Right! Note

You’ll become clearer about prototypes after working through a couple of examples later in this chapter.

What this boils down to is that the way of the Object object is the way of all objects in JavaScript. The examples in the remainder of this chapter should help give you a feeling for what this means.

Somewhat more specifically, the methods of the Object object are present in all objects in JavaScript. The Object method you’re most likely to encounter is the toString method, present (although sometimes undefined) in all objects. The toString method returns a string conversion of an object as best it can. For example, the toString method of a number returns a string representation of a number.

The following statements:

 var theNum = new Number(42);  var theStr = theNum.toString(); 

store a string representation of theNum in the variable theStr, namely 42, which you can then display:

 document.write(theStr); 

You can also write this more compactly, like so:

 var theNum = new Number(42);  document.write(theNum); 

Under the covers, theNum is being converted to a string just the same, using the Number object’s toString method even if it isn’t explicitly invoked.

It’s a good idea to define the toString method for any custom objects you create, as I show you in the “ Creating Objects ” section of this chapter.

If the toString method hasn’t been defined for an object, it generally returns the string [object] —which isn’t really very useful!

Advanced Note

The valueOf method is also a method of the Object object and is used when JavaScript needs to convert an object to a primitive type that isn’t a string, most often a number. You can define your own valueOf methods for your own objects, and it makes sense to do so in some circumstances.




Learn How to Program Using Any Web Browser
Learn How to Program Using Any Web Browser
ISBN: 1590591135
EAN: 2147483647
Year: 2006
Pages: 115
Authors: Harold Davis

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net