OOP

Textbook Chapter 3: Object-oriented Programming

Special Note About This Page (and Textbook Chapter 3 on OOP)

Students without object oriented programming experience may find this chapter to be the hardest chapter in the textbook. DO NOT GET DISCOURAGED OVER THIS CHAPTER! If you are relatively new to programming, learn what you can from this chapter within reasonable time constraints (One Week at the most), study the bold, blue exam hints, and move on. You will be able to do client and server side scripting without a complete understanding of object oriented programming.

Introduction

In the last chapter, we learned how to use the write METHOD of the document OBJECT to write HTML content and client-side scripts to a Web page. The document is an example of an object that is built into the browser software. The document object contains a method call WRITE, which we used to write output to a Web page.

When we passed a string parameter to the write method which sent it to the browser, we did not have to know the code that created the document object or the write method. We just needed to know the syntax for using the object.

Object Oriented Programming allows us to use objects that can be accessed by other programs, including Web pages. An OBJECT is a set of related methods and properties that are compartmentalized. A METHOD contains one or more programming statements.

We can define a method within a Web page, but if a method is defined within an object, the code can be reused in many Web pages. Objects can have properties, which can be assigned values from programs. The object property can be assigned different values each time for each object that is created.

JavaScript Programming syntax:

  • A pair of curly braces { } surrounds all statements within a function
  • End each statement or command with a semicolon ( ; )
  • the var keyword is used to declare variables in JavaScript

The following example demonstrates the process of creating an object and using the object within a Web page. The code creates a banner object, which can be reused in other Web pages. Here it is in ACTION. See the code below:

<html>
<head>
<title>Custom Banner</title>
<script language = "javascript">

function Lamp(txtAd) {      //Create the object name Lamp
this.bannerAd = txtAd;      //Create a property called bannerAd
this.show = display;        //Create a method called show
}

function display() {                 //Create the display function
document.writeln(this.bannerAd);
}
</script>
</head>
<body>
<h1>Lamps for Sale</h1>
<script>
var ad = "Sale Today!<br>"  //Declare a variable named ad and assign                             //it a text message
theLamp = new Lamp(ad)      //Create a new lamp object name theLamp                             //and pass ad to it
theLamp.show()              //Call the show method of the new object
</script>
</body>
</html>

We can change the contents of the ad variable to "All lamps marked 50% off regular price!" by changing:

var ad = "All lamps marked 50% off regular price!<br>"

Here it is in ACTION.

Although we could display this text with less code in HTML, without creating a banner object, this example demonstrates how to create an object and how to use the newly created object in a Web page. You'll see the benefit in a moment.

Creating a Custom Object

Creating a custom object consists of two separate tasks:

  1. Create the object definition
        - the code that contains the methods and properties of the object
  2. Create a new instance of the object
        - can call any of the methods defined in the object definition
        - can assign properties that were declared in the object definition

In the example above, the object definition is located in the script, in the head section of the Web page. The newly instantiated object is created in the body section of the Web page.

The process is like making cookies. If you have a recipe to make cookies, you know all the ingredients and you know how to combine the ingredients to make the cookies. But, a recipe is not a cookie. When you create the cookie dough, and then bake it, it becomes an edible cookie. In the same way, the object definition contains the directions for creating an object, but just as the cookie must be baked, an object must be instantiated before it exists.

Creating the Object Definition

The object definition is created by a constructor function. A function is a named grouping of one or more programming statements. A constructor function is a special type of function that can create new objects. In our example above, to create the lamp object, we created a constructor function using the function keyword. One argument was passed to the constructor function in the parentheses. This argument was used to assign a value to a property of the lamp object.

Adding a Property to the Object Definition: Object properties are identified by the name of the object followed by a period, followed by the name of the property. In the example above, we only created the object definition, so we cannot refer to the object by its name. The keyword THIS can be used in place of the object name. After we create an instance of the lamp object, we can refer to it by the object's name.

The syntax for assigning a value to a property of an object is:

Object.Property=Value

Adding a Method to the Object Definition: Besides storing data in properties, objects can also perform functions on themselves and other objects. A method is a function that is called from within an object. A method can accept any number of required or optional input arguments.

To add a method to an object, name the method and then assign the method to a function. In our example above, the code this.show refers to the name of the lamp object's method, which will display the banner message. The this.show method is assigned to a function called display.

The syntax for naming a method is similar to the syntax for naming a property. In JavaScript and VBScript, we can access those methods by using the following syntax:

Object.Method(arguments)

Tip: Name methods with action words to reinforce the concept that methods are functions that perform actions.

Using Custom Objects

We cannot directly access an object definition. Instead, we must instantiate the object by declaring a new instance of the object. The object definition is used as a template for creating the new object. We can create many objects from the same object definition. The ability to assign different values to each object's properties is called encapsulation. Each object inherits the properties and methods from the object definition.

Instantiating New Objects

Instantiation is the process of declaring and initializing an object. There are two steps to instantiating a new object:

  1. Specify the new name for the object
  2. Assign the new object to the object definition created earlier, using the new keyword

Object names must be unique.

Encapsulating Code Within Objects

Encapsulation means that the inner workings of the object (its methods and properties) are maintained within the object.

Encapsulation provides an interface by which you can access the methods and properties of an object. We can create multiple objects within the same page based on the same object definition, as long as the names are unique.

Object Inheritance

By creating a new object with an object definition, the new object maintains the same characteristics as the original object. This is called inheritance. Objects inherit the properties and methods of the original object. If an object does not assign a value to a property, and a new object is created without assigning a value to the property, the property is assigned the default value, "undefined."

Adding Properties and Methods to an Object

We can extend new objects with additional properties or methods. For example, we can add another property for the Lamp2 object called lampColor and display it with the document.write method. This property is not available to the first object because it was an additional property defined only in the second object.

Let's add the following code immediately above the closing body tag:

<script language="javascript">
theLamp2.lampColor = "Red";
document.write(theLamp2.lampColor);
</script>

See it in ACTION.

Notice that the syntax to display a property of an object is: ObjectName.PropertyName.

Using Custom Objects to Encapsulate

We can save time and make Web applications easier to maintain and update by using objects to separate the business rules and data. Fig. 3-1 (on page 80 in our text) demonstrates how object oriented programming can be used to isolate business logic. By isolating business logic (such as shipping charge formula), if the formula needs to be changed, or if it becomes more complex, it only needs to be changed in the shipping object. The rest of the Web applications does not need to be reprogrammed.

Ready for a POP QUIZ?

Using Built-In Objects

Browser software contains built-in objects. We can access these objects, along with their properties and methods. This hierarchal collection of objects follows a standard known as the Document Object Model or the Browser Object Model. The WWW Consortium sets the standards for the DOM.

We can access all of the objects, properties, and methods within the DOM using client-side scripting.

Browser Incompatibility

Not all browsers meet the current DOM standards. Although all browsers have built in DOMs, not all properties and methods are supported across browsers. The best way ensure your scripts will work is to preview the Web pages in all Web browsers in question.

Object Hierarchy Within the Document Object Model

All objects within the DOM have a position within the DOM hierarchy. The WINDOW object has the topmost position in the object hierarchy. The WINDOW can contain many child objects, such as the HISTORY object, the LOCATION object, the EVENT object, the SCREEN object, the FRAMES object, and the DOCUMENT object.

Some objects contain one or more child objects. For example, the WINDOW object contains the NAVIGATOR object, the HISTORY object, the FRAMES object, the LOCATION object, and the DOCUMENT object.

The figure on the right illustrates the entire collection of objects within the DOM and their hierarchical relationship.

The DOCUMENT object contains its own set of child objects, including the FORMS collection. A collection allows more than one object of the same type to coexist within the same object model hierarchy - which means there can be multiple FORM objects with one DOCUMENT object. The multiple forms are referred to as the FORMS COLLECTION, also known as the forms[] array.

An array is a collection of objects. Each object is numbered according to its sequential position in the array. The objects in an array are numbered, starting with zero. This number is known as its index and is used to identify each element (in this case, each form) of the array.

The first element of the form array can be identified as form[0]. Subsequent forms can be identified as form[1], form[2], etc.

The DOM contains several other collections, including the images collection and the form element collection. If there are several images on a document, you can refer to each image by its position within the image collection, for example img[0], img[1], etc.

Forms contain different types of form elements, such as text boxes. These elements make up the form element array. Each element in the form is also numbered sequentially, starting with zero.

Naming Conventions for Objects in the DOM

To refer to an object in a script, we can use the fully qualified name for the object. The fully qualified name includes the name of the object and its hierarchical position within the DOM. For example, a textbox object named lname is in a form called form1 on a Web page. The fully qualified name for this object would be window.document.form1.lname.

If you are referring to an object within the current window, you don't have to identify the window object. Therefore, you could also refer to the text box object as document.form1.lname .

To refer to the property of an object, use the name of the object followed by a period and the name of the property. For example, to refer to the contents of the text box named lname, use the value property. You can use the fully qualified name, window.document.form1.lname.value , or if the object exists within the current window, use document.form1.lname.value . Because the name property of an object is used to refer to the object within scripts, you should assign each object a unique name.

Properties, Methods, and Events

Each object and collection contains its own set of properties, methods and events. Some are common among all objects, like the name property. We can assign values to some properties and some are read-only, which means we cannot change their values.

To retrieve the value of a property of an object, use the complete name of the object. For example, to retrieve the value of a text box called uid, which is on a form named loginForm, and assign its value to a variable named txtMyvar, you could use txtMyvar = document.LoginForm.uid.value .

To assign a value to an object, you would also use the complete name of the object. For example, to change the label value on a button named btnSubmit, which is on a form named form1, you could use the code btnSubmit.value = "Submit Me".

Objects within the DOM have built-in methods that can be called from scripts. Calling a method is very similar to setting or obtaining a property value. To call a method, use the complete name of the object, followed by a period and the name of the method. For example, to close a window using the close method, you could use window.close().

Arguments can be passed to the method. In chapter 2, we passed a string as the argument to the write method of the document object. You can call the write method with window.document.write("Welcome") or document.write("Welcome"). Before you call a method, ask yourself if it requires any inputs or returns any outputs.

Some built-in methods return a value to the script that called them. In the following example, when the user places the mouse pointer over the first hyperlink, the window status will change to the new string. When the user places the mouse pointer over the second hyperlink, the status message will not be altered; instead, the filename will appear. The return false statement will stop the browser from displaying an error message. The return true statement catches the error and continues to process the script.

<a href="product1.htm"
     onMouseOver="window.status='Claddagh Ring';
           return true">
New Ring</a>
<br>
<a href="product2.htm"
    onMouseOver="window.status='Claddagh Earrings';
    return false">
New Earrings</a>

Here are the links appearing in the browser:

New Ring
New Earrings

Notice the status bar at the bottom of the browser window when the mouse is over each link. The only difference between the two links are that one uses return true and the other uses return false.

Events allow the object to interact with the programmer, and allow objects to interact with the program itself. Users interact with Web pages by performing actions called events, such as clicking, scrolling, and entering information into a text box. The command statements that respond to an event are called the event handler. This event handler can contain code that is executed when the event occurs.

When the user clicks an object, the onClick event is fired for that object. In the following example, an alert box will open when the user clicks the button.

<form name="form1">
<input type="button" name="btnCall1"
      value="Click Here for Help"
      onClick=window.alert("1-800-555-1212");>
</form>

Here is the button. Try it out.

In this second example, we use a function named callUs, to handle an event.

<form name="form2">
<input type="button" name="btnCall2"
       value="Click Here for Help"
       onClick="callUs()";>
</form>
<script language="javascript">
function callUs() {
      window.alert("1-800-555-1212")
}
</script>

Here is the button. Try it out.

In the third example, we will use VBScript. Also, we will access these events in the DOM directly. Notice that the name of the procedure is a combination of the name of the object, an underscore, and the name of the event.

<form name="form3">
<input type="button" name="btnCall3"
value="Click Here for Help">
</form>
<script language="vbscript">
sub btnCall3_onClick()
     window.alert("1-800-555-1212")
end sub
</script>

Here is the button. Try it out. You must be running IE in order for VBScript to run. This is why we will ALWAYS use JavaScript for client side scripting. We're learning VBScript here so that we'll be ahead when we get to ASP server side scripting in chapter 5.

We will talk more about functions and procedures in later chapters. For now, here is a list of events and their event handlers:

Event

Applies to

Occurs when

Event handler

Change
text fields, textareas, select lists User changes value of element
onChange
Click
buttons, radio buttons, checkboxes, submit buttons, reset buttons, links User clicks form element or link
onClick
DragDrop
windows User drops an object onto the browser window, such as dropping a file on the browser window
onDragDrop
Error
images, windows The loading of a document or image causes an error
onError
KeyDown
documents, images, links, text areas User depresses a key
onKeyDown
KeyPress
documents, images, links, text areas User presses or holds down a key
onKeyPress
KeyUp
documents, images, links, text areas User releases a key
onKeyUp
Load
document body User loads the page in the Navigator
onLoad
MouseDown
documents, buttons, links User depresses a mouse button
onMouseDown
MouseMove
nothing by default User moves the cursor
onMouseMove
MouseOut
areas, links User moves cursor out of a client-side image map or link
onMouseOut
MouseOver
links User moves cursor over a link
onMouseOver
MouseUp
documents, buttons, links User releases a mouse button
onMouseUp
Move
windows User or script moves a window
onMove
Reset
forms User resets a form (clicks a Reset button)
onReset
Resize
windows User or script resizes a window
onResize
Select
text fields, textareas User selects form element's input field
onSelect
Submit
forms User submits a form
onSubmit
Unload
document body User exits the page
onUnload

Are we ready for another Pop Quiz?

The Windows Object

The window object is the highest level of an object that can exist in the DOM and it represents the physical space that holds your HTML document. The window object provides a direct link to many of the capabilities of the browser. 

The Window Object Properties

Common window properties include 

  1. self - reference to the current window
  2. name - used to refer to a specific window
  3. defaultStatus - sets the default string on the status bar
  4. status - temporarily sets the contents of the status bar

The Status Property of the Window Object:

Check out THIS code that changes the status message.

The Window Object Methods

  • Multiple windows can be opened at the same time
  • Open and Close method used to open and close windows within the browser
  • scroll method scrolls down the window to a specific coordinate within the window
  • Only one window can be active at a time
  • The active window has focus (keyboard attention)
  • Focus method makes the window the active window
  • Blur method removes focus
  • Blur and Focus are methods used with other objects, such as text boxes

Opening and Closing Windows: The open window method allows us to open a new browser window (existing page or a new page). The syntax follows:

window.open(URL, WindowName, WindowFeatures, Replace)
  • URL is web address
  • Window Name is name assigned to the window (can later refer to that window in a script by its name)
    The keyword NULL or "" (double quotes) can be used in place of the window name
  • Window Features is a string of options and their values that modify the layout of the window
  • Replace argument loads the page within the current window

Window Features offers the following options (which is a list of names and values, delimited by commas):

  • location (on or off)
  • menubar (on or off)
  • toolbar (on or off)
  • directories (on or off)
  • status (on or off)
  • scrollbars (on or off)
  • Top and Left (in IE only) specifies Top and Left position of the window in pixels
  • Resizable

The following code produces the window that opens when you click the button below the code:

window.open('http://www.harrised.com/209/','cis209', (on same line)
'status=off,toolbar=off,location=off,height=200,width=350');

The window object open and close methods are used to increase user involvement in the Web page. Check it out by clicking on the 282ln03windowOpen.htm file link.

Creating Window Dialog Boxes:

Dialog boxes are used to obtain information from the user, or to provide the user with information. There are three window methods that create dialog boxes:

  1. alert - used for simple messages like must enter last name (OK button)
  2. confirm - use to require user to accept or reject some condition (OK and CANCEL button)
  3. prompt - used to obtain information from the user (OK and CANCEL button, and an input box)

Alert Dialog Box

The alert( ) method displays a dialog box containing a message and an OK button. The syntax for the alert( ) method is:

alert("Message");

where Message is the message that will appear in the alert dialog box. For example, the following code:

<input type="submit" value="Show Alert" onClick="alert('This field is required');">

will produce the following dialog box when the SHOW ALERT button below is clicked:

Confirm Dialog Box

The confirm( ) method displays a message in a dialog box which has both an OK button and a CANCEL button. If the user clicks the OK button, the value TRUE is returned. If the user clicks the CANCEL button, the value FALSE is returned. The confirm( ) method is ideal when you want a simple YES or NO answer from a user. They syntax for the confirm( ) method is:

confirm("Message");

   OR   

variable = confirm("Message")   to set variable equal to the user's choice (true or false)

where Message is the message that will appear in the confirm dialog box. For example, the following code:

<input type="submit" value="Show Confirm"
onClick="answer=confirm('Submit Data?');alert('You answered '+answer);">

will produce the following dialog box when the SHOW CONFIRM button below is clicked:

Prompting User For Input

The prompt( ) method creates a dialog box containing a message, and an input field into which the user can type a value or text string. The syntax for the prompt( ) method is:

prompt("Message", "Default_Text");    the DEFAULT TEXT argument is optional

   OR   

variable = confirm("Message")    to set variable equal to what the user typed in the text box

where Message is the message that you want to appear in the dialog box, and Default_Text is the default text you want to appear in the dialog box's input field. For example, the following code:

<input type=submit value="Click Color"
onClick="prompt('What is your favorite color?','type color here');">

will create the following button:

This button is really useless since it does not capture the value that the user types into the dialog box. Also, the DEFAULT TEXT argument is optional, some browsers will require that you place two sets of quotes in place of the argument. For example:

prompt("Message", "");

will provide the prompt( ) dialog box without default text.

In most cases, you will want to capture the value that the user enters into the prompt( ) dialog box. If the user clicks the CANCEL button, the value returned will be null. We should plan for this possibility by using the IF condition to test for a null value. Also, there is a possibility that the user might click OK or press the ENTER key before typing in a color. In this case, the value returned will be an empty string (""). We should plan for this possibility as well. For example, we could use the following code:

<script>
function CheckColor() {
varColor = prompt("What is your favorite color?","");
if (varColor != null) {
       if (varColor == "") {
              alert("You left it blank!");
       } else {
              alert("I like the color "+varColor+" too!");
       }
}
}
</script>
<input type="submit" value="Click Color" onClick="CheckColor();">

to produce the following CLICK COLOR button which will respond back with the color if the user types in a color. It will respond back with a message saying that the user left it blank if they click OK or press ENTER without typing in a color. Finally, if the user clicks CANCEL, presses the ESCAPE key or clicks the CLOSE button on the dialog box, it will respond differently. It will simply close the box and not respond at all.

 

Note that the double equal signs (==) are used to compare two statements in JavaScript. The double equal signs are used to check whether one expression is equal to another.

Window Event Handlers

You can indicate a function to be executed, which allows you to execute a group of JavaScript statements.
<body onLoad = "startCode()">

Since a Web page is a document object within the window object, we can access the event handlers through the document object using document.load and document.unload . For example we could use:

<body onLoad="alert('Welcome to this page!')" onUnload="alert('Goodbye!')">

as in THIS example. You don't really want to annoy your visitors with these alert boxes. This example demonstrates the use of event handlers, providing us feedback with alert boxes as we learn.

Are we ready for another POP QUIZ?