Previous page
BACK

Part 3 - Objects
(Properties, methods & objections!)

 
Contents
  1. OOPs
  2. Objects in your browser
  3. The DOM (document object model)
  4. A pre-defined miscellany!
  5. Summary

Introduction

Here we find out about the skeleton of JavaScript - the various objects and their components that go to make up a web browser and the pages it displays. By the time you've read through this page, you should have a good basic grasp of all the important objects that make up JavaScript. Only in the next page will we put meat on the bones. (You'll then find that working through the previous pages was invaluable)! But first a note about OOPs..

OOPs

On our first page, we made brief reference to 'Object-Oriented Programming' (OOP). What is this, how did it all come about and is it worthwhile? We already know that 'Objects' generally have associated properties and methods, and have even used some of these. Here, we look at OOP in more detail, find out why JavaScript isn't a true example of OOP, and learn why this isn't necessarily a bad thing. (We already know that there is nothing that you can do with OOP, that you cannot do with more 'old-fashioned' programming).

OOP is generally thought of as having the following properties:

  1. Encapsulation;
  2. Polymorphism;
  3. Inheritance.

Let's examine each of these in turn.

Encapsulation

Encapsulation is pure commonsense. It it very reasonable (whether you subscribe to an OOP paradigm or not) to make sure that a 'module' or section of program has a high degree of internal 'cohesion', but when it talks to another module, it is 'loosely coupled' to that module. What do I mean by all these fancy terms? Let's use an example to illustrate what I mean.

Let's say I have two programs, we'll call the programs DataManager and ScreenShow. DataManager manages a database, ScreenShow shows things on the screen. As a user, I want some arcane information shown to me on my screen, so I ask ScreenShow to do this task for me. ScreenShow needs to talk to DataManager to get the information she requires. Now let's consider how she might do this. She might:

  1. Send a message to DataManager saying "When you have a moment, send me the following information through this convenient data pipe I've provided";
  2. Call a routine she knows exists within DataManager that causes DataManager to interrogate the database, and provide the information;
  3. Viciously hijack DataManager, writing program instructions into the area where DataManager works and coercing DataManager into giving up the necessary information!

Obviously there are many other possibilities, but which do you think is the best? Clearly the first option, which is an example of "loose coupling". The monstrous third option is an outrageously obvious example of "tight coupling". The first option also embodies the concept of "information hiding", which simply means that when you interrogate a module, you don't have to know about the internal workings of the module to gain useful information. In fact, it's often a bad idea to know, or have to know, much about how the module works - rather just ask your question! It is also clear that a hostile program (for example, a virus) is more likely to be able to injure a module if it has access to the inner workings of that module.

Encapsulation is a good thing!

Polymorphism

Here, the basic idea is that different types of information can be handled by the same method as a sort of natural extension of the method. Think about it - if you have a method called Add that can add two integers, it makes sense to be able to use the same method to add two floating point numbers. Used with responsibility and care, polymorphism is a reasonable idea.

Inheritance

Superficially, this seems a great idea. You start off with simple, concrete, (earthy?) prototype objects, and then you refine them by defining more and more abstruse objects that inherit the properties of their prototypes. Sounds great, huh?

Mmph. This idiot is not convinced, especially when an object can inherit different properties from several different prototypes. Things rapidly become hideously complex. In addition, some of these properties can be changed in the more refined and abstruse child of a simple, easily understood base object. This quickly causes confusion, and cockups.

We suspect that one of the three reasons why modern programmers screwed up so badly on projects like Denver International Airport, why (with practically unlimited funding) nobody seems capable of constructing a replacement for the thirty year old software that administers air-traffic control, and possibly even why (we are told) certain fly-by-wire aircraft have had unexplained little crashes, is because of unquestioning acceptance of flashy new philosophies (Only our ignorant opinion).

Inheritance is a nightmare.

Why JavaScript isn't a fully-fledged example of OOP

You'll be glad to learn that JavaScript (unlike C++, and Java, which is to a certain extent an emasculated form of C++) is not OOP. JavaScript is not fully encapsulated (a bad thing) but is redeemed by not having true inheritance either!

Objects in your Browser

There is a pre-defined hierarchy of objects in every browser. You can also define your own objects within the context of this hierarchy. Here we will look at the pre-defined objects in Netscape and IE. We will start with "top-level" objects (the backbone of JavaScript), move on to major properties of the window object (the limb girdles and ribs) and then focus in on the properties of the document object (in our fanciful analogy, the hands of JavaScript). There are only two "top-level" objects in your browser. They are:

TOP LEVEL OBJECTS
Netscape-specific
Microsoft-specific
window object
Contains:
navigator object
Contains:
window.frames (array of frames)
window.location (current URL)
window.document (the DOM)
window.name
window.parent (if a frame)
window.self (self-referential = window.window)
window.top (top level, for e.g. nested frames)
window.status (status bar text)
window.defaultStatus

window.closed 1.1 (boolean, true if was closed)
window.history 1.1 (user's prior browsing)
window.opener 1.1 (which object opened me?)
window.screen 1.2 {user's display}

window.innerHeight / .innerWidth / .outerHeight / .outerWidth 1.2
window.locationbar / .menubar / .personalbar / .scrollbars / .statusbar / .toolbar 1.2
window.pageXoffset / .pageYoffset 1.2
window.crypto / .offScreenBuffering 1.2
navigator.userAgent
navigator.appVersion
navigator.appCodeName
navigator.appName

navigator.platform 1.2

navigator.language 1.2
navigator.plugins 1.1
navigator.mimeTypes 1.1
navigator.userLanguage {IE 4}
navigator.systemLanguage {IE 4}
Methods of the window object include:
  • alert()
  • confirm()
  • prompt()
  • open()
  • close() (close the window)

  • focus() / blur() 1.1
  • setInterval() / clearInterval() 1.1
  • setTimeout() / clearTimeout() 1.1
  • moveBy() / moveTo() 1.2
  • resizeBy() / resizeTo() 1.2
  • scrollBy() / scrollTo() 1.2
  • find() / home() / print() / stop() 1.2
  • scroll () 1.1 = scroll to specific window coordinates (deprecated).
  • atob(), btoa() 1.2 = decode base-64-encoded data string or (btoa) encode.
  • back(), forward() 1.2 = undo last history step in any frame ( =history.back() ); forward moves on.
  • captureEvents(), releaseEvents(), handleEvent(), routeEvent() 1.2 (See part7)
  • crypto.random() 1.2 = return pseudo-random string.
  • crypto.signText() 1.2 = return encoded data string, a 'signed object'
  • enableExternalCapture(), disableExternalCapture() 1.2
  • setHotKeys() 1.2 = 'enable or disable hot keys in a window which does not have menus'
  • setResizable 1.2 = enable this property
  • setZOptions 1.2 = set Z-order stacking behaviour of window.
navigator methods include:

  • javaEnabled() 1.1
  • taintEnabled()
    1.1 {data-tainting security model!}
  • preference()
    1.2 {signed scripts can configure this!}
  • savePreferences()
    1.2 {save preferences to prefs.js}

(Okay, we lied to you. There are other top-level objects. For example in Netscape there is the Packages object {v 1.1}, which allows you to actually access Java! The three Java 'classes' that you can access are java, netscape and sun. The Packages.netscape class is particularly interesting, so much so that there is a top level synonym for it called (surprise, surprise) the netscape object. But don't worry about all this fine print - it is unlikely to affect you. )

The above lists are pretty intimidating. Fortunately, we can trim them down considerably. First, we'll briefly glance through the navigator object - we've in fact used most of the relevant information that we can get from this object in the first page of our tutorial! Next, we'll look at the more challenging window object, with its multitude of properties and methods.

1. The navigator object

There are no events associated with the navigator object. It tells us about the browser. The Navigator.appCodeName is pretty useless. The appName tells us whether we are working with say MSIE or Netscape. The appVersion should give us both version and operating system. userAgent gives us more details about the browser. mimeTypes is an object in its own right (associated with Netscape plugins) {It has properties .type, .description, .enabledPlugin, .suffixes and .length}. Similarly plugins is an array of installed plug-ins { with properties .name, .filename, .description, .length}.

2. The window object

2.1 Methods

Most of the above window components (e.g. window.document) have a host of associated properties and methods. Before we look at them, let's look at some of the methods associated with window. You know some already:

  • alert is an old friend!
  • confirm is almost identical to alert, but allows you to click on a cancel button. As you would expect, if you click on cancel, confirm returns false; it returns true if you click on OK. Useful, isn't it?
  • prompt is even more useful. A user can enter a string!
Note that there is NO WAY that you can get rid of the irritating "JavaScript Prompt" header to these boxes, nor can you prevent these boxes from suspending all web-page activity until they are answered!

Most of the other methods are self-explanatory, and infrequently used. But let's talk just briefly about:

  • window.open() - Use this method to open a new browser window. It takes four arguments:
    1. the URL of the document to display;
    2. a window name (can load to an existing window!);
    3. window size and decorations!
    4. boolean true/false = replace old entry / create new (if opening to an existing window).

    An example of open()
    (after Flanagan's 'Definitive Guide' )
    var winobj = window.open("tinywin.html", "tinywin",
                             "width=200,height=150,status=yes,resizable=yes");
    

    We'll discuss window.open() in a lot more detail in our tutorial on 'playing with windows', which you'll encounter at the bottom of this tutorial page!

  • window.close() - Note that this method will generally only work if the JavaScript code created the window you're closing - otherwise the user will be asked whether he/she indeed wants to close it! See how both window.open() and window.close() should be written with window in front of them (There are other similar methods within the document object)!

  • window.focus() makes the stated window the focus of keyboard activity (and window.blur() relinquishes this). Only in JavaScript 1.1 and above.

2.2 Properties

Now let's start looking at the various window properties.

First we'll dispense with some of the simple ones:

  1. window.status - You have access to the text on the status bar of your browser! You can even reset it! Try clicking on the following link:

    <A HREF="err.htm" onClick="status='You clicked me';return false">

    What we've done here is to attach an anchor that is exactly the same as the text on the screen. If you click on the link, then the status bar changes, but the link is NOT followed - all because we said return false. Take note that returning false cancels the default action that one would expect, so the branch to the page err.htm is not taken!

    You can use defaultStatus to provide a default message, set up when the user loads a webpage (as we did on this page).

  2. window.screen is unfortunately only found in JavaScript 1.2 (You could check that the user is running 1.2 (how?) and then use the properties of this object to determine what images will fit on the screen, and so on! A pity earlier versions didn't have this. The relevant properties are .availWidth and .availHeight. There is also a .colorDepth, which is the log2 of the number of colours available).

  3. window.location represents the current document being displayed. It in turn has several properties:
    • .href
    • .protocol
    • .host
    • .pathname
    • .search - anything in a URL after a question mark. You can use this property (rather than our clumsy #hash) to transfer information between scripts!
    • .hash (Where have we come across this before)?

    Take note of the following code (from our first and second pages):

    Setting a new location

            location="part2.htm" + "#" + whoyou;
    

    See how JavaScript more-or-less breaks it's own rules - rather than using a method, we have this crude (official!) way of moving to another page! Only in JavaScript 1.1 were two methods added to the window.location object to allow some fiddling with page loading. They are:

    • location.reload()
    • location.replace()

    We used the replace() method in our transition page between our first tutorial and the second one. Pity if you're using IE3, however. Take note that there is also a document.location which is pretty useless, and is in fact usually the same as window.location.href ( replace() was added in JavaScript version 1.1, and open() was altered in the same version to clear existing document content!)

    Note that, to be pedantic, you should actually specify window.location.href = something, as some browsers could otherwise mis-interpret what you mean.

  4. window.history is quite variable from browser to browser, and is generally protected from prying eyes (as it says where the user has been)! You can however use the following methods:
    • back()
    • forward()
    The third method (go) is best avoided; the above two do the same as clicking on the relevant browser buttons. As an aside, note that go(0) reloads the page - you will sometimes encounter this.

  5. The window.frames object is exciting, complex, and highly confusing, so we'll defer deep exploration of it until later. (As an aside, you can check whether frames are present - if frames.length is zero, there are no frames).

  6. window.name - JavaScript generally makes little distinction between windows and frames; you'll find that it's generally important to name a frame that you create (or a window that you open) so that later on such objects can talk to one another! Most important is the use of such a name in <a> anchors and <form>'s - the TARGET="name" option in such HTML code allows you to specify the name of the window where you want results displayed! (We talk about targets in part five).

Whew! What's left? Well, the biggie is:

The document Object and DOM

There has recently been much talk about a new fancy standardised "Document Object Model" or DOM, provided by the World Wide Web consortium (W3C). We won't talk about that here (It's meant to be fully implemented in IE5 and Netscape 6, aka gecko). Here we will be more simple:

The document object
(Corresponds to the <body> tag)
Netscape-specific
Microsoft-specific
Properties Methods
Property What it is Method What it does
anchors 1.1 array of all <a> anchors close() close 'stream'
applets 1.1 array of all applets open() open 'stream'
area a contained image map write() write to document
bgColor, fgColor, linkColor, vlinkColor, alinkColor various colours writeln()
cookie The value of a cookie captureEvents(), releaseEvents() 1.2 See part7
forms 1.1 array of forms handleEvent(), routeEvent() 1.2
embeds, plugins 1.1 array of plugins.. contextual() 1.2 contextual selection criteria are used to specify a Style object
images 1.1 array of images getSelection() 1.2 return current text selection
domain 1.1 (domain name of server)  
links array of links
title These should be intuitively obvious
history
lastModified
referrer
URL
classes 1.2 contains style objects specifying HTML tag styles
ids 1.2 id attributes of HTML tags
layers 1.2 contains an entry for each layer
tags 1.2 also specifies HTML tag styles!
height, width 1.2 document dimensions in pixels
all all the document components!
activeElement, body, defaultCharset, fileCreatedDate, fileModifiedDate, fileUpdatedDate fileSize, frames, location, mimeType, nameProp parentWindow , protocol, readyState, scripts, security, selection, styleSheets (Whew!)
{all the event handlers} These include: onafterupdate, onbeforeupdate, onclick, ondblclick, ondragstart, onerrorupdate, onhelp, onkeydown, onkeypress, onkeyup, onmousedown, onmousemove, onmouseout, onmouseover, onmouseup, onreadystatechange, onrowenter, onrowexit,onselectstart

Quite a list, but with mercifully few methods! We've highlighted the most important properties in green. We'll look at these in detail, but first the methods. You should for the time being, at least, ignore the Netscape and Microsoft-specific properties. Eventually you'll be forced to know a few of them, but most are irrelevant, or even dangerous!

You already know how document.write works! We used it on page two of our tutorial to write a personalised message to a web-page. open() and close() are extensions of this sort of idea, and writeln() just writes to a document, followed by a "\n" character, which you also understand perfectly. Let's look at document.open(). This is used to clear the current document - you can then use document.write() to write to it, and finally close off the document with document.close().

In some JavaScript tutorials, you will read that document.write() automatically clears and opens the document if you're writing for the first time. This is generally true, but occasionally you might get bitten if you don't first document.open(). Also note that you will have trouble if you open a document, write to it, and then forget to close the document!

Later on we'll explore multiple windows and frames in detail, and you'll find out the true power of these methods. (Did you know that you can even dynamically write an image - for example, a GIF file - to a window?)

Note that the document.open() method has two entirely optional arguments. these are:

  1. mimeType, and
  2. replace
The default MIME type is text/html, but several others can be specified. Built in MIME types are:
  • text/html ASCII text with HTML formatting.
  • text/plain Plain ASCII text with end-of-line characters to delimit displayed lines. HTML formatting is not rendered; instead, the tags are displayed in the document.
  • image/gif A GIF image file.
  • image/jpeg A JPEG image file.
  • image/x-bitmap An XBM image file.
Other MIME types will force the loading of a plug-in. The replace parameter, if specified, 'causes the new document to reuse the history entry that the previous document used'.

Let's look at the important document components.

This document contains..

The above table looks pretty trivial (it is!) but was actually dynamically generated using a JavaScript within the body of the web-page you're reading! (Note that it only summarises the components up to the point where the information is written - for example, a form that appears later in this document is completely ignored! We'll eventually find out how to overcome this sort of limitation).

Each of these important elements of the document object is an array of items. You are already familiar with the HTML equivalents of most of these items - links, forms, images and so on. Each item is itself an object, with properties and methods. Be careful - there is massive redundancy in how you can refer to these objects. For example, let's say we have a form called "fred", the first form on our page. We can refer to fred as:

document.forms[0]

OR as document.fred

OR indeed as document.forms["fred"]

(How confusing). Let's look at these document elements in more detail:

  1. anchors and links are arguably the most important components of any document. These two arrays describe:
    • All the anchors that exist within a document (made for example using
      <a name="anchorname">);
    • All the references (links) to other web-pages, etc.

    The simpler of the two is the list of anchor objects. Anchors have no properties, methods or events - they just keep track of all named offsets within a web page. anchors.length gives us all of the document's anchors. You will not often use the anchor objects.

    The link object is a lot more complex. Fortunately, we've encountered most of its properties before, during our tinkering. Here they are:

    link properties
    Property Meaning
    href The whole URL
    pathname the pathname part of the url
    protocol the protocol e.g. http: or ftp:
    host, hostname and port (More redundancy! host = hostname:port)
    hash The #name part of the URL
    search Everything after a "?" in the URL
    target The window where the document will be loaded, if specified!

    A list of link properties for the first link on this page!

    The above table is (again) a table containing the dynamically generated properties of the first link in the current web-page (The link at the top of the page that points back to the preceding page in our tutorial). You may wish to view the source to see that I'm not cheating - look for #FF6633, the lurid background colour of this and the preceding table.

  2. applets refer to Java applets contained in the page. We won't talk about them now, nor will we discuss:

  3. embeds which are embedded plug-ins.

  4. forms are more fun. Here are their properties:

    form properties
    Property Meaning
    action (specifies where form data are sent - a common destination is e.g. "/cgi-bin/FormMail.pl" - to a Perl script)
    elements Each form element is represented here! (See below)
    length Tells us the number of elements
    encoding (MIME encoding - don't worry about this now)!
    method (how is information sent to the server? "GET" or "POST" - POST is usual, submitting the data to the standard input stream of the CGI script)
    name useful in referring to the form by name
    target Say where 'responses' should go (usually the name of a window)

    Don't be too scared by this list. We won't examine forms in any detail yet, but at the end of the fourth page of our tutorial, we present a small digression where we actually construct and use a form step-by-step. (We thought it was best to wait until you have a firm grasp of form-related events).

    The methods for the form are few and only mildly interesting - they are limited to reset() and submit(), the meanings of which are obvious,
    and handleEvent() which, is Netscape-specific, passing control to a specified event handler.

    Let's talk about the form elements. In our skeleton form on page 1 of our tutorial, we learnt about a few form elements. Here's the complete collection:

    form element types
    (most created with <INPUT type="{fill in type here}">
    apart from <select> and <textarea> types )
    Type of element What it does Properties
    button
    • name
    • type
    • value
    checkbox (<---- Click on me!)
    • checked
    • defaultChecked
    • name, type, value
    hidden (A hidden field, not displayed, but used to send hidden information to the final destination of the form data)
    • name, type, value
    password
    (Type something in the box)
    • defaultValue
    • name, type, value
    radio (Click me too!)
    • checked
    • defaultChecked
    • length
    • name, type, value
    reset
    (Click me after changing a few other fields)
    • name, type, value
    select
    • length
    • options
    • selectedIndex
    • name, type
    submit (Do NOT click me)
    • name, type, value
    text
    • defaultValue
    • name, type, value
    FileUpload
    (used to upload a file - the name is typed in!)
    • name, type, value
    textarea
    • defaultValue
    • name, type, value

    You can see that form elements are a powerful adjunct to JavaScript - and vice versa! The full power of this association will only be revealed later.

  5. The images array stores information about all the images on the page, as follows:

    image properties
    Property Meaning
    src The path where the image file is found, as specified in the SRC="filename.gif" part of the <img > tag
    width, height Image pixel dimensions - fixed!
    border value of BORDER="" attribute. This border thickness in pixels cannot be altered.
    complete (Did the image load completely?)
    hspace, vspace, lowsrc (Correspond to these HTML image attributes - the space around an image and low resolution image source)
    name Yep, the image can have a name!
    prototype You can add your own user properties to the image too!

    Pretty boring for the most part, aren't they? The image object also has NO methods associated with it. You would think that was it, but you would be wrong! For JavaScript has one more sneaky trick up its sleeve - you can make new objects. Look at the following - it's called a constructor

    An example of the Image() constructor
        myReserveImage = new Image();
        myReserveImage.src = "whatever.gif";
    

    What did we just do? We set aside a new object, giving it a name and then loading an image into the object. It looks cute, it has some uses, but such objects are not accessible through the document.images array.

    What do you do if you want to alter an image that's already displayed on a page? Most of the image properties in the table above can only be read. However, two can be altered, and when you alter them, the image changes. The two properties that can be altered are src and lowsrc. You can generally forget about lowsrc, but altering src has a dramatic result - the old image is replaced by the new one specified as the value of src. So you can change an image once it's displayed on screen. One caution however - if you load an image that differs in size from the original one, the new image is squeezed or stretched to fit onto the procrustean bed of the old image!

    Finally let's look at the properties of an image using document.write() as we did for links above:

    Sample image properties for an image on this page

    (Why does my version of MSIE 4 not get the height and width correct? Why does Netscape 4 have complete as "false"?)

A pre-defined miscellany

Oops! Almost forgot!

Apart from our old friend Math, there are two other general-purpose, overly complex object types that are in equal measure irritating and useful. The are:

  1. Date
  2. String

Each has a wealth of associated methods. So many, in fact, that we thought it advisable to explore these methods on separate pages. If you wish to do so, click on the above links! Be warned - they are complex, and you can always come back later.

Summary

The objects contained in your browser are legion, but fit into two big containers - the window object, and the navigator object. The first of these is perhaps more important, if only because it contains the vitally important document object, which is used not only to display web pages, but also to organise the structure that underlies them - the anchors and form elements (and so on) that we use to create our pages. We now know enough to carry on and find out about events in PART FOUR of our tutorial.

(Alternatively, you might first wish to play with windows a bit - this is fun, and without trying it, you won't really understand how to make irritating pop-up windows that drive people away from your website. We explore the window.open() method in some detail. We also look at how one can set a timer to do something repetitively, or after a delay)!


Webpage author jvs@anaesthetist.com Last update: 2000-10-7