Previous Contents Next
8. JavaScript Objects

Objects, Properties, and Methods

Up to this point you have seen how JavaScript creates and manipulates data values that you explicitly declare. You define variables, populate them with numeric and string data, and use various operators and statements to process the data for the results you want. Coincidentally, and with little explanation, you have also used various language elements that are "built into" JavaScript. You have used Alert and Confirm boxes, forms elements, documents, windows, mathematical and string functions, and other features of the JavaScript environment that are there for your use without your having to do anything special to create or use them. You have, in fact, been using various JavaScript objects to assist in your processing.

"Objects," in the formal sense of the term, are the "nouns" of the JavaScript processing environment. They include the windows in which you work, the documents you display, the forms you process, the variables you declare. Associated with these objects are properties. In other words, objects have characteristics that describe them. For example, a window has size, shape, and frame properties that describe how it looks; a document has a background color, text style, and form components that describe it; a form has characteristics given by the kinds of data fields and buttons defined for it. Throughout the JavaScript environment are various objects and their properties that are used to put together a processing application.

Objects also have methods associated with them. Methods are the "verbs" of the processing environment. They are the actions associated with the objects--functions that the objects can perform. For example, documents have open, close, and write methods. That is, a document can be opened in a window, it can be closed and removed from a window, and it can be written to. A button has a click method associated with it such that some action can be taken when it is clicked. A text string, even, has several methods associated with it to change its properties or to find particular substrings.

Thus, JavaScript objects--those that are built into the language and those that you create when writing scripts--have properties that describe them and methods that manipulate them. As a script author, you can change the properties and use the methods to help you carry out your processing.

Referring to Object Properties and Methods

You refer to an object's property with the notation:

objectname.propertyname

That is, an object's property is referenced by appending the property name to the object name with a period (.). For example, length is one of the properties of a text string. So, if you declare the variable:

var TextString = "This is a string."

you refer to its length property as

TextString.length

If you display this property, say, in an Alert box:

alert ("\nThe length of TextString is " + TextString.length)

the following message is displayed:

You refer to an object's methods in the same way. For example, one of the methods associated with a text string is named toUpperCase ( ). This is a method (a built-in processing "function," if you wish) to change the characters in a string to all upper case letters. If you want to apply this method to the above TextString variable, you would do so with the notation:

TextString.toUpperCase ( )

You append the name of the method to the name of the object with a period.

Some of the properties of objects can be changed; others cannot. Some objects have numerous methods associated with them; other do not. We'll proceed through each of the objects in the JavaScript environment, detailing their properties and methods and, along the way, describing how to access and use them. We'll begin with the so-called "built-in" objects, those that are part of the browsing environment irrespective of the particular windows, documents, forms or other objects that might be associated with your application. On subsequent pages we'll discuss those objects that depend somewhat on the features that you build into your web pages.

The navigator Object

The navigator object is a reference to the browser being used to view a web page. This object has five properties as named and described in the following table. For each property, a button is provided to display the property for the browser you are currently running:

onclick = alert ( "\n" + navigator.property ).

Properties of the navigator Object
Property Description Setting
appCodeName The browser's code name.
appName The browser's application name.
appVersion The browser's version number in the format: version (platform; I [international] or U [U.S.]).
appUserAgent Information sent from the browser to the server when requesting a web page.
javaEnabled Indicates whether the browser is capable of working with Java and, if so, whether the capability has been enabled.

 

There are no methods associated with the navigator object. However, you can use the property information to help you adapt your scripts to different browsers. For instance, you can check the appVersion property to see if the browser being used is version 3.0. If so, then you can include JavaScript statements that take advantage of its capabilities. On the other hand, if you find out that the user's browers is not the latest version, you can either skip the statements or do something different. The following script illustrates this idea:

<SCRIPT>
if ( navigator.appVersion.indexOf ( '3.0' ) != -1 ) {
     ...do this if Version 3.0...
else {
     ...do this if not Version 3.0... }
</SCRIPT>

This script uses a string method named indexOf ( ) (which we'll discuss later) to see if the character string "3.0" is included somewhere within the appVersion property. If it is, the method returns the position in the string where this substring is located; if not, it returns a value of -1. So, if the returned value is not -1, we know that "3.0" is somewhere within the appVersion property string. The if statement makes this test and then either runs the code for browser version 3.0 or runs the code for an earlier version. You could also check this property for the substring "Win" to see if the user is running in a Windows environment.

Objects and Instances

A JavaScript object exists as an "idea" and as a "reality." If this sounds a little Platonic, it really is. There is the abstract, ideal Form of an object, and there is the the everyday, tactile reality of a particular object based on that Form. In JavaScript, the first of these is called an object class; the second, an object instance. The object class exists as a model, or blueprint, for creating objects; the object instance is the actual object created by your browser when you open a web document.

In most cases, an object instance is created for you. For example, when you open a web page, the browser automatically creates an instance of a document object based upon the document class. Using the document class as a blueprint, the browser creates your particular document instance containing all the properties and methods associated with the document class from which it was built. In other cases, you must create an object instance before you can access any of the associated properties and methods. This was the case on the previous page when you created an array. JavaScript has an array class--a general definition of an array, or a general model for its structure and use; you needed to create an instance of that array class--an actual array based on that blueprint--to make it accessible by your scripts.

Don't get too bogged down in trying to differentiate classes from instances. This is not a tutorial on object-oriented programming (OOP) where you need of firm grasp of these concepts. Still, there are instances (the old-fashioned kind) where you will need to create an instance (the new-fashioned kind) of an object before using it. When that happens you should know, simply, that you are creating an actual object from the JavaScript blueprint.

The Date Object

One object that is not automatically created for you is the Date object. You have to fashion an instance from the Date class before you can work with dates and times. This is done by assigning a new instance of the class to a name:

TheDate = new Date ( )

This command gets the current date and time from the computer and makes them available through the name TheDate (or any other name you wish to assign). This particular command is a script element in this document, and the instance TheDate is referenced in the examples below. The date object doesn't have any properties associated with it, but it does have several methods. A method is referenced in the same way as a property--by appending it to the name of the object with a period:

TheDate.method ( )

The following table lists some useful methods associated with the Date object. (You may need to refresh your screen to update a method if you click on a button more than one time.)

Methods of the Date Object
Method Description Setting
getDate ( ) Returns the day of the month:
TheDate.getDate ( ).
getDay ( ) Returns the day of the week (Sunday = 0):
TheDate.getDay ( ).
getHours ( ) Returns the hour of the day:
TheDate.getHours ( ).
getMinutes ( ) Returns the minute of the hour:
TheDate.getMinutes ( ).
getMonth ( ) Returns the month (January = 0):
TheDate.getMonth ( ).
getSeconds ( ) Returns the seconds of the minute:
TheDate.getSeconds ( ).
getYear ( ) Returns the current year (last two digits):
TheDate.getYear ( ).
toLocaleString ( ) Converts the full date to a string (MM/DD/YY HH:MM:SS):
TheDate.toLocaleString ( ).
setDate ( ) Changes the day of the month (in the Date object, not in the computer); the day to change to is passed as a parameter:
TheDate.setDate ( 15 )
 
setHours ( ) Changes the hour of the day (in the Date object, not in the computer); the hour to change to is passed as a parameter:
TheDate.setHours ( 3 )
 
setMinutes ( ) Changes the minutes of the hour (in the Date object, not in the computer); the minute to change to is passed as a parameter:
TheDate.setMinutes ( 30 )
 
setMonth ( ) Changes the month (in the Date object, not in the computer); the month to change to is passed as a parameter (January = 0):
TheDate.setMonth ( 6 )
 
setSeconds ( ) Changes the seconds of the minute (in the Date object, not in the computer); the seconds to change to is passed as a parameter:
TheDate.setSeconds ( 10 )
 
setYear ( ) Changes the last two digits of the year (in the Date object, not in the computer); the year to change to is passed as a parameter:
TheDate.setYear ( 99 )
 

 

The Math Object

The Math object includes properties and methods to perform mathematical calculations. The properties include mathematical constants; the methods include mathematical computations. Both can be used in combination with the mathematical operators that we covered earlier.

Properties of the Math Object
Property Description
E Returns the base of natural logarithms (approximately 22.718).
LN2 Returns the natural logarithm of two (approximately 0.693).
LN10 Returns the natural logarithm of ten (approximately 2.302).
LOG2E Returns the base 2 logarithm of e (approximately 1.442).
LOG10E Returns the base 10 logarithm of e (approximately 0.434).
PI Returns the ratio of the circumference of a circle to its diameter (approximately 3.14159).
SQRT1_2 Returns the square root of one-half (approximately 0.707).
SQRT2 Returns the square root of two (approximately 1.414).

 

One quick example of the use of these constants: the area of a circle is given by Area = Math.PI * Radius * Radius ( Area = pi * radius2 ).

The following table gives the Math methods. The general format of these methods is:

Math.method ( parameter )

where the value to which the method is applied (a variable, literal, or mathematical expression) is enclosed as a parameter within the parentheses.

Methods of the Math Object
Method Description Results
abs ( ) Returns the absolute value of a number:
Math.abs ( -100 )
acos ( ) Returns the arc cosine of a number (in radians):
Math.acos ( .90 )
asin ( ) Returns the arc sine of a number (in radians):
Math.asin ( .90 )
atan ( ) Returns the arc tangent of a number (in radians):
Math.atan ( .90 )
ceil ( ) Returns the integer value next above a decimal number:
Math.ceil ( 3.25 )
Math.ceil ( -3.25 )

cos ( ) Returns the cosine of a number (in radians):
Math.cos ( .90 )
exp ( ) Returns enumber:
Math.exp ( 2 )
floor ( ) Returns the integer value next below a decimal number:
Math.floor ( 3.25 )
Math.floor ( -3.25 )

log ( ) Retuns the natural logarithm of a number:
Math.log ( 2 )
max ( ) Returns the greater of two numbers:
Math.max ( 3, 1 )
min ( ) Returns the lesser of two numbers:
Math.min ( 3, 1 )
random ( ) Returns a pseudo random number between zero and one:
Math.random ( )
round ( ) Returns a number rounded to the nearest integer:
Math.round ( 1.25 )
Math.round ( 1.50 )
Math.round ( 1.75 )


sin ( ) Returns the sine of a number (in radians):
Math.sin ( .90 )
sqrt ( ) Returns the square root of a number:
Math.sqrt ( 144 )
tan ( ) Returns the tangent of a number:
Math.tan ( .90 )

 

The String Object

Each string object that you create in a script (either a literal or variable string) has properties and methods associated with it. These are listed in the following tables. As with previous properties and methods, the dotted format is used:

object.property
object.method ( )

Some of the string methods are passed parameters, which appear between the parentheses; some have no parameters.

Properties of the String Object
Property Description Results
length Returns the number of characters in a string (the string can be a variable or literal):
"This is a string.".length

 

Methods of the String Object
Method Description Results
anchor ( name ) Changes the string into an HTML anchor using (name) as its label; used when writing to a document:
"This is a text string.".anchor ( "Label" )
big ( ) Changes the text in a string to HTML big font; used when writing to a document:
"This is a text string.".big ( )
blink ( ) Changes the text in a string to HTML blinking font; used when writing to a document:
"This is a text string.".blink ( )
bold ( ) Changes the text in a string to HTML bold font; used when writing to a document:
"This is a text string.".bold ( )
charAt ( index ) Returns the character at ( index ) position of a string, counting from 0:
"This is a text string.".charAt ( 8 )
fixed ( ) Changes the text in a string to HTML fixed-pitch font; used when writing to a document:
"This is a text string.".fixed ( )
fontcolor
("color")
Changes the text in a string to an HTML color; used when writing to a document:
"This is a text string.".fontcolor ( "BLUE" )
fontsize ( size ) Changes the text in a string to an HTML size; used when writing to a document:
"This is a text string.".fontsize ( 2 )
indexOf
("chars")
Returns the position of ("chars") in the string, counting from 0; can also use ( "chars", from ) to specify position to begin searching from:
"This is a text string.".indexOf ( "text" )
"This is a text string.".indexOf ( "s", 7 )

italics ( ) Changes the text in a string to HTML italics; used when writing to a document:
"This is a text string.".italics ( )
lastIndexOf
("chars")
Returns the position of ("chars") in the string, searching from the end of the string; can also use ("chars", from) to specify the position to begin searching from, counting from the end of the string:
"This is a text string.".lastIndexOf ( "text" )
"This is a text string.".lastIndexOf ( "s", 7 )

link ( "href" ) Turns the string into an HTML link using ("href") as the URL; used when writing to a document:
"This is a text string.".link ( "page.html" )
small ( ) Changes the text in a string to HTML small font; used when writing to a document:
"This is a text string.".small ( )
strike ( ) Changes the text in a string to HTML strikethrough font; used when writing to a document:
"This is a text string.".strike ( )
sub ( ) Changes the text in a string to HTML subscript font; used when writing to a document:
"This is a text string.".sub ( )
substring
(index1,index2)
Returns a substring starting with character (index1) and ending at character (index2), counting from 0; character (index2) is one position beyond the last character included in the substring:
"This is a text string.".substring ( 10, 14 )
sup ( ) Changes the text in a string to HTML superscript font; used when writing to a document:
"This is a text string.".sup ( )
toLowerCase ( ) Returns a string in lower-case letters:
"This is a text string.".toLowerCase ( )
toUpperCase ( ) Returns a string in upper-case letters:
"This is a text string.".toUpperCase ( )

 

Several of the string methods are used to format text when writing to an HTML document. These can be illustrated by opening a new, secondary document and writing the strings to it. The following script is used for this example:


<SCRIPT>
function WriteMessages ( )
{
    var String = "This is a text string."

    Win1=open ("","secondary","scrollbars,width=350,height=350")
    Win1.document.open ( )
    Win1.document.write ( "<CENTER><H3>String Methods</H3></CENTER>" )
    Win1.document.write ( "String.big ( ) = " + String.big ( ) + "<BR>" )
    Win1.document.write ( "String.blink ( ) = " + String.blink ( ) + "<BR>" )
    Win1.document.write ( "String.bold ( ) = " + String.bold ( ) + "<BR>" )
    Win1.document.write ( "String.fixed ( ) = " + String.fixed ( ) + "<BR>" )
    Win1.document.write ( "String.fontcolor ( 'Red' ) = " + String.fontcolor ( "Red" ) + "<BR>" )
    Win1.document.write ( "String.fontsize ( 3 ) = " + String.fontsize ( 3 ) + "<BR>" )
    Win1.document.write ( "String.italics ( ) = " + String.italics ( ) + "<BR>" )
    Win1.document.write ( "String.link ( 'page.html' ) = " + String.link ( "page.html" ) + "<BR>" )
    Win1.document.write ( "String.small ( ) = " + String.small ( ) + "<BR>" )
    Win1.document.write ( "String.strike ( ) = " + String.strike ( ) + "<BR>" )
    Win1.document.write ( "String.sub ( ) = " + String.sub ( ) + "<BR>" )
    Win1.document.write ( "String.sup ( ) = " + String.sup ( ) + "<P>" )
    Win1.document.write ( "<A HREF='p08.html' onclick='self.close()'>Close</A>" )
    Win1.document.close ( )
}
<SCRIPT>


That pretty much covers the properties and methods associated with JavaScript's built-in objects. Beginning on the next page we'll start looking at those objects for which instances are created when you call for them in your scripts.


Previous Contents Next