Object Oriented Programming s1

Total Page:16

File Type:pdf, Size:1020Kb

Object Oriented Programming s1

OBJECT-ORIENTED PROGRAMMING

Overview

This chapter discusses object-oriented programming. You will learn how to create objects, instantiate objects, and use properties, methods, and event handlers associated with those objects. Then you will learn to create Web pages that interface with the objects.

Object Oriented Programming

Object-oriented programming allows programmers to access objects, properties, methods, and functions of an object without having to know about how the objects are created.

Object-oriented programming creates applications that are easily maintained and that work well with other applications.

Consider the following code section:

Lampbanner.htm Custom Banner

Lamps for sale

View Lampbanner.htm

Object-Oriented Programming 1 Explanation of Code

Creating an object named Lamp using the keyword function. Function Lamp(txtAd) The lamp object is being passed one argument, txtAd.

This is a property inside the function. The txtAd variable is this.bannerAd = txtAd; assigned to the bannerAd property. this.show = display; This is creating a method called show

Creating a function called display, display receives no Function display(){ arguments

The var keyword is used to declare a variable in JavaScript. var ad = “Sale today! This line is declaring a variable named ad and assigning the
”; text message, “Sale today!
” to that variable.

This line creates a new Lamp object using the keyword new and names the theLamp = new Lamp(ad); object theLamp. It also passes the variable ad that is declared above to the Lamp object

This line is calling the show method of the new object. Notice the method is theLamp.show(); referred to using the name of the new object, theLamp, and the name of the method, show.

Object-Oriented Programming 2 Modify the above file with the value of the Ad variable, as shown below. The variable ad is used to change the value of txtAd argument of the Lamp object. This does not change the property of the object, only the value of the object.

Lampbanner2.htm

Custom Banner

Lamps for Sale

View Lampbanner2.htm

Object-Oriented Programming 3 Object Definition (Creation of a Custom Object) Creation of a custom object consists of two steps:

 The first task is to create the object definition. The object definition is the code that contains the methods and properties of the object

 The second task is to create a new instance of the object. For the lamp example:

Step 1: Create the object definition by

function Lamp(txtAd){ this.bannerAd = txtAd; this.show = display; }

Step 2: Create a new instance of the object.

theLamp = new Lamp(ad);

Both steps are needed so you can call any of the methods that were defined in the object definition.

Note, the object definition is created by using the reserve word function. A function is a named grouping of one or more programming statements.

Object-Oriented Programming 4 Object Properties

Object properties are identified by the name of the object followed by a period, followed by the name of the property.

ObjectName.propertyName = value

Example: theLamp.bannerAd = “Sale Today!”

Until the instance of an object is created (in step 2 above), one cannot refer to the object by its name. But, one can refer to the object with the keyword “this”.

theLamp.bannerAd

theLamp Object name

bannerAd Property name

this.bannerAd this Object name

bannerAd Property name

Object-Oriented Programming 5 Object Methods

Objects may have methods. A method is a function that is called from an instance (a copy) of an object. For example, a method could be used to manipulate the properties of the object.

To add a method to an object, name the method and then assign the method to a function. The syntax for naming a method is: objectName.methodName = function name

Example:

theLamp.show = display; function display (){ document.writeln (“Hello world”); }

Some methods simply perform their actions when they are called, while other methods require more information before they can be processed.

A method can accept any number of required and optional arguments.

theLamp.show(ad)

theLamp Object name

show Method name

(…) Arguments

Object-Oriented Programming 6 Object Instantiation

The creation or defining an object does not mean that one can access it directly. One needs to create an instance of the object, then only it can be accessed.

Instantiation is the process of declaring and initializing an object. For example:

1. Specify a new name for the object.

a. TheLamp

2. Assign the new object to the object definition created earlier, using the new keyword.

a. new Lamp(ad);

The total instantiation process looks like this:

theLamp = new Lamp(ad);

If we want to instantiate another object, we can do that with a new name.

aLamp = new Lamp(newad); /* newad is a new variable

Now we have theLamp and aLamp, two instances of the Lamp object.

The methods of the object can be called by using the name of the instance. For example:

theLamp.show(); aLamp.show();

Object-Oriented Programming 7 Object Encapsulation

Encapsulation means that the properties and methods of an object are maintained within the object. Creating new objects does not change any of the properties and methods.

That is, the object is encapsulated from any change of property values, so the same object can be used again and again.

In the following example, two instances of the Lamp object, theLamp and theLamp2, are created. Both instances use the same method show(), but the property of the object, bannerAd, is assigned a different value by changing the value of the Ad variable.

Lampbanner3.htm Custom Banner

Lamps for Sale

//Define a variable and a new instance of the object //Refefine the variable and a different instance of the Lamp object

View lampbanner3.htm

Object-Oriented Programming 8 Object Inheritance

All new objects created from the same object definition will maintain the same characteristics as the original object. This characteristic of objects is known as object inheritance.

You are not required to access all the properties and methods of the original object, but they are available, if they are needed.

Object-Oriented Programming 9 Adding Properties and Methods to an Instance of an Object

Although an instance of an object inherit all methods and properties of the object, but one can define additional methods and properties to the object instance.

In the example below, a new property lampColor is added to the instance theLamp2 of the Lamp object and assigned a value “red”.

Lampbanner4.htm Custom Banner

Lamps for Sale

View lampbanner4.htm

Object-Oriented Programming 10 Using Built-In Objects

Browser software contains built-in objects termed as the Document Object Model (DOM). Using client-side scripting, programmers can access all of the objects, properties, and methods within the Document Object Model (DOM).

Not all browsers meet the current DOM standards. Netscape Navigator and Microsoft Internet Explorer do have built in DOMs, Quick but not all properties and methods are supported across browsers. Fact: The best way ensure your scripts will work is to preview the Web pages in all Web browsers in question.

All of the objects within the DOM have a position within the DOM hierarchy. The window object has the topmost hierarchy. The window object has many child objects and so on the Navigator and document objects.

Window

Navigator Location History Frame

Plugin Document Mime Type

Image [] Form [] Link []

Hidden Text Anchor []

FileUpload Textarea Layer []

Radio Reset Area []

Select Submit Applet []

Button Options [ ] Plugin []

Object-Oriented Programming 11 The document object contains its own set of child objects. The document object contains a form collection (a set). That is, there can be multiple form objects within one document object. The form collection contain other objects such as Text, Checkbox, and radio. Each form on a document is identified by its name. Each object on a form is first identified by the form name, and then by the object name within the form.

Each object and collection in the DOM contains its own set of properties, methods, and events.

Properties

Some properties can have values assigned to, and some are read-only properties. For example, the name property of an object can be assigned a value.

If the object is within the current window, you do not need to identify the name of the current window. For example, to retrieve a value of a text box named lastName, use the value property of the text box: document.form2.lastName.value = txtName or document.form2.lastName = txtName, /*value is default property where txtName is the value typed by the user on the text box.

Object-Oriented Programming 12 Methods

Objects within the DOM have built-in methods that can be called form scripts. For example, to close a window using the close method, you could use window.close().

Argument can be passed to the method. For example, as we have seen before

Document.write (“Welcome to UHCL”)

Events

Users interact with the Web page by performing actions called events, such as clicking, scrolling, and entering information.

The command statements that respond to an event are called the event handler.

For example, when a user clicks an object, an event called onClick is generated for that object.

Object-Oriented Programming 13 The following is a list of events and their event handlers:

Event Applies to Occurs when Event handler Change text fields, textareas, select User changes value of element onChange lists

Click buttons, radio buttons, User clicks form element or link onClick checkboxes, submit buttons, reset buttons, links

DragDrop windows User drops an object onto the browser onDragDrop window, such as dropping a file on the browser window

Error images, windows The loading of a document or image onError causes an error

KeyDown documents, images, links, text User depresses a key onKeyDown areas

KeyPress documents, images, links, text User presses or holds down a key onKeyPress areas

KeyUp documents, images, links, text User releases a key onKeyUp areas

Load document body User loads the page in the Navigator onLoad

MouseDown documents, buttons, links User depresses a mouse button onMouseDow n MouseMove nothing by default User moves the cursor onMouseMove

MouseOut areas, links User moves cursor out of a client-side onMouseOut image map or link

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 onReset button)

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

Object-Oriented Programming 14 An Example of Event Handler The following code will catch the click event using three different ways. Note, the document uses three forms, a button object in each form that has properties name and value.

The first method uses the onClick event handler for the button object. The second method uses a function callUs. The third method uses onClick event of the button object (a subroutine in VB).

Status Test

Call Customer Support

View Customer.htm

Object-Oriented Programming 15 The Window Object

The window object represents the browser window, the physical space that holds the HTML document. The properties and methods associated with it are handled through the window object.

Explanation Property Syntax self window.self Reference to the current window.

name window.rightwindow Reference to a specific window that can be called by name. default window.defaultstatus = Allows you to set a default message in the status “print this” status bar. status window.status = “print Allows you to change the message in the this” status bar.

Opening and Closing Windows

The open window method allows you to open a new browser window on the fly. For example:

window.open(“new.html”, “newWindow”, “height=200, width=200, status=no, toolbar=no, menusbar=no, location=no”)

window.open Opens a new window “new.html” The new URL that will be opened in the new window “newWindow” The name of the new window “height= 200, These are the Windows options starting with height and width width=200 Turning off the status bar, a value of 1 or yes would turn it status=no, back on toolbar=no, Turning off the toolbar, a value of 1 or yes would turn it back menusbar=no, on location=no” Turning off the menusbar, a value of 1 or yes would turn it back on Turning off the location bar, a value of 1 or yes would turn it back on

To close a window, pass the name of the window that is to be closed to the window method. To close the current window use:window.close();

View WindowOpen1.htm View WindowOpen2.htm

View WindowCreate.htm

Object-Oriented Programming 16 The Document Object

The document object is a child object of the window object. The document object allows direct access to the current Web page.

While the window object represents the actual browser window, the document object represents the actual Web page within the window.

Document Object Properties

Property Description alinkColor The color of the active hyperlinks on the Web page. Default is red. An active hyperlink is clicked but not yet visited background Identifies a background image to use bgColor The background color. If you have an image in the background, then this property will override the image. cookie The document’s cookie. defaultClientScript The default client scripting language - - usually JavaScript defaultServerScript The default server-side scripting language - - usually VBScript domain The domain name of the Web page that provided the Web page fgColor The foreground color, used for text and headings lastModified The date the Web page was last modified or changed linkColor The color of the hyperlinks on the Web page. Default is blue. referrer The URL of the referring page text The default text color title The text string that will be displayed in the caption bar url The URL of the current page vlinkColor The color of the visited hyperlinks on the Web page. Default is purple.

The cookie property allows one to store and read cookies that are associated with the document. A cookie consists of a cookie name and a value. The syntax to write a cookie:

Document.cookie = “cookie name = value”; Examples: Document.cookie = “userID = Rob123”;

Document.cookie = “userID = Rob123”; expires = Monday, 01- Jan-02 12:00:00 EST”;

To read a cookie into a variable named readCookie:

ReadCookie = document.cookie;

Object-Oriented Programming 17 Document Object Methods

The document object methods are used before, such as write and writeln. The syntax is:

document.write (“string”);

Example:

document.write (“Today is “ + Date());

Method Description captureEvent Only available in Netscape Navigator, is used to capture events that need to be handled. write Allows you to write text, HTML tags, expressions, and variables to your page. writeln Same as Write, but it adds a carriage return to the end of the line.

Document Object Event Handlers

Like window object, the document object responds with document handlers Thus when a user clicks on page, the onClick event is triggered.

Event Handler Description onClick Action performed when the user clicks a button onDblClick Action performed when the user clicks a button twice onKeyDown Action performed when the user presses a key onKeyPress Action performed while the user holds a key onKeyUp Action performed when the user releases a key onMouseDown Action performed when the user presses the mouse button onMouseUp Action performed when the user releases the mouse button

Object-Oriented Programming 18 The Form Object (Collection)

The form object is one of the most commonly used objects in the Web programming. The document object is the parent to the form object.

There can be multiple forms in a document. Each form can be assigned a unique name.

Each form typically contains multiple child objects or sometimes called elements. These are input, select, password, reset, checkbox, radio, and so on.

Form Properties

The forms collection has several properties. The syntax to retrieve a form property in a document:

document.[formName].property

The syntax to retrieve the property of an element within the form:

document.[formName].[elementName].property

Object-Oriented Programming 19 Form Methods There are two methods of form object: submit and reset.

Methods Description submit Submits the form without requiring the user to click the Submit button reset Submits the form without requiring the user to click the Reset button

The Form Child Objects

There are many child objects to a form such as the input, select, button, and image. These objects are used within a form, of a document, to collect information, display image, select values, and so on.

Object-Oriented Programming 20 The Input Object

The input object is used to create a text box and other form elements. When the type property of input is set to text, a text box is created, and can be used to retrieve data from the user, or display information.

A textbox must be declared in the HTML section before it can be manipulated by the script code.

The properties of the textbox:

value, defaultvalue, form, name, and type.

There are three methods to the input object. They are:

blur, focus, and select.

The focus method makes the text box active.

The select method makes the text box active and highlights the text in the box, which allows the user to change it.

Object-Oriented Programming 21 Example of text boxes:

Form Properties

Login Form

Username
Password  

View formLogin

Object-Oriented Programming 22 The Select Object

The select object is used to create a list box or of drop down box in a form. A list box displays all items in the list. A drop-down box does the same thing but it hides the list.

Example of a drop-down list:

Select List

View selectList.htm

Object-Oriented Programming 23 DISCUSSION TOPICS

 Discuss why most programming languages are going to object- oriented programming.  Discuss the importance of encapsulation to object-oriented programming.  Discuss the Document Object Model and select real life situations where programmers might use some of the objects in the model.  Search the Web for instances of the DOM being used and discuss the techniques behind the uses.

KEY TERMS

 Array – a collection of objects.  Concatenation – a process of combining text, HTML tags, expressions, and variables within the same string.  Constructor function – a special type of function that can create new objects.  Document Object Model (DOM) – objects that are built-in browser software.  Encapsulation – the inner workings of the object, such as its methods and properties, are maintained within the object.  Event handler - the command statements that respond to an event.  Function – a named grouping of one or more programming statements.  Inheritance – new objects maintain the same characteristics as the original object.  Instantiate – process of declaring a new instance of an object.  Method – contains one or more programming statements, if defined within an object it can be reused in many Web pages.  Object – a set of related methods and properties that are compartmentalized.  Object definition – is the code that contains the methods and properties of the object.  Object-oriented programming – allows you to use objects that can be accessed by other programs, including Web pages.

Object-Oriented Programming 24 Quiz:

1. What is the programming philosophy that allows you to access objects, properties, methods, and functions of an object without having to know about how the objects are created? 2. What is the keyword to declare a variable in JavaScript? 3. What is the keyword to create a new instance of an object? 4. What is the name of the characteristic that all new objects will maintain the same characteristics of the original object? 5. What is a collection of objects, such as forms[], known as? 6. What is the Hierarchical collection of objects that are built in the browser software called? 7. What is the highest level of the DOM called? 8. What are the user interactions with a Web page called? 9. What are the command statements that respond to user events called? 10.What is the highest level of the DOM? 11.How do you refer to the current browser window? 12.How do you print text to the status bar at the bottom of the window? 13.Can you open a browser window without all the graphical user interface components such as the toolbars? 14.What property of the navigator object identifies the name of the client’s browser application? 15.Which object provides information about the URL of the current document? 16.Can you send the user back or forward more than one page at a time? 17.Which object represents the actual Web page within the window? 18.What is the property called to change the color of the background of a Web page? 19.What is the difference between the methods document.write() and document.writeln()? 20.What is the code to reference the fifth form on a Web page?

Object-Oriented Programming 25

Recommended publications