extensively revised by Scott McCaughrin (work in progress) | Previous | Next


Working with Objects

JavaScript is based upon a simple non-class, object-based paradigm. An object is a construct with properties that are JavaScript variables and functions. The variables may be other objects, and the functions belonging to an object are termed its methods.

NOTE: You have just seen two major differences between Java and JavaScript: unlike Java, objects in JavaScript are not class instances, and not all functions need to be methods.

In addition to objects that are pre-defined in the Navigator client and the server, you can define your own objects. This chapter describes how to use objects and how to create your own objects.

This chapter contains the following sections:


Objects and Properties

A JavaScript object has properties associated with it. You access the properties of an object with a simple dot-notation:

objectName.propertyName

Both objectName and propertyName are case-sensitive. You define a property by assigning it a value. For example, suppose there already exists an object named myCar. You can assign it additional properties named make, model, and year as follows:

myCar.make = "Ford"
myCar.model = "Mustang"
myCar.year = 1969;

You may recall that an associative array or hash-table is an array of key-value pairs, whose elements may be indexed by the character-string keys instead of by numeric subscripts. This is how objects are implemented in JavaScript: the object's name is just the associative array-name, its property-names are the character-string keys, and the object's property-values are the values associated with the keys.

So, for example, you could access the properties of the myCar object as follows:


myCar["make"] = "Ford";
myCar["model"] = "Mustang";
myCar["year"] = 1967;

where the key-value pairs in hash-table myCar are: ("make","Ford"), ("model","Mustang"), and ("year",1967). As another example, the following function displays the properties of any object when you pass the object and the object's name as arguments to the function:


function ShowProps( obj, obj_name )  // returns list of property names and values
{
     var result = "";   // cumulative list
     for( var i in obj ) // 'i' ranges over property-name keys
        { // obj[i] = property-value corresponding to key 'i'
          result  +=  obj_name  +  "."  +  i  +  " = "  +  obj[i]  +  "\n"
        }
     return result
}

So the function call ShowProps( myCar, "myCar" ) would return the following:

myCar.make = Ford
myCar.model = Mustang
myCar.year = 1967

Creating New Objects with Initializers

JavaScript has a number of pre-defined objects. In addition, you can create your own objects. In JavaScript 1.2, you can create an object using an object initializer. Alternatively, you can first create a constructor function and then instantiate an object using that function with the new operator.

You can create objects directly using an object initializer, which is an expression consisting of property:value pairs. Using object initializers is sometimes referred to as creating objects with literal notation. ("Object initializer" is consistent with the terminology used by C++.)

The syntax for creating an object using an object initializer is as follows (with requisite lexemes in boldface):


objectName = { property1:value1, property2:value2, ..., propertyN:valueN }
where objectName is the new object's name, each propertyI is an identifier (a name, number, or string literal), and each valueI is an expression whose value is assigned to propertyI. Note the absence of operator new: it is not needed here.

If an object is created with an object initializer in a top-level script, JavaScript interprets the object each time it evaluates the expression containing the object literal. In addition, an object initializer used in a function is created each time the function is called.

The following statement creates an object and assigns it to the variable x if the expression cond is true:

if( cond )  x = { hi:"there" }
If cond == true, then x.hi == "there".

The following example creates myHonda with three properties. Note that the engine property is itself an object with properties of its own.

myHonda  =  { color:"red", wheels:4, engine:{cylinders:4,size:2.2} }

Thus, myHonda.color == "red", myHonda.wheels == 4 and myHonda.engine.cylinders == 4.

You can also use object initializers to create arrays. See Array Literals (page 37) in the Client-Side JavaScript Reference.

JavaScript 1.1 and earlier versions. You cannot use object initializers. You can only create objects using constructor functions or else using a function supplied by another object for that purpose.

Creating New Objects with Constructors

Alternatively, you can create your own object using a constructor function, which is a JavaScript function you write and call to construct your object. Then the object creation process consists of these two steps:

  1. Define your object's type by writing a constructor for it. Unlike Java, you don't need a class with constructor -- only the constructor.
  2. Allocate an instance of your object with operator new applied to an invocation of your constructor (just like Java).
That is, to first define your object's type, you write a constructor for it that specifies its

For example, suppose you want to create an object type for cars. You want your object's type-name to be car, and you want it to have properties make, model, year, and color. To do this, you would write the following function:


function car( mk, mdl, yr )
{
     var make = mk;
     var model = mdl;
     var year = yr;
}
Now you can create an object called mycar as follows:

mycar  =  new car( "Eagle", "Talon TSi", 1993 );
This statement allocates mycar and assigns it the specified values for its variables. Then, the value of mycar.make is the string "Eagle" and of mycar.year is the integer 1993.

You can create any number of car objects this way. For example,

kenscar  =  new car( "Nissan", "300ZX", 1992 )
somecar = new car( "Mazda", "Miata", 1990 )
An object can have a variable that is itself another object. For example, suppose you define an object type called person with the following constructor:

function person( name, age, sex )
{
     this.name = name;   // 'this' refers to the
     this.age = age;     // current object when
     this.sex = sex;     // it has been new'd
}
and then instantiate two person objects as follows:


rand  =  new person( "Rand McKinnon", 33, "M" );
ken   =  new person( "Ken Jones", 39, "M" );
Then you can re-write the definition of car to include an owner property that takes a person object as value:


function car( make, model, year, owner )
{
      this.make = make;    // string
      this.model = model;  // string
      this.year = year;    // integer
      this.owner = owner;  // object-type = 'person'
}
To instantiate the new objects, you then use the following:


car1  =  new car( "Eagle", "Talon TSi", 1993, rand );
car2  =  new car( "Nissan", "300ZX", 1992, ken );
Notice that instead of passing a literal string or integer value for the last argument when creating the new objects, the above statements pass the objects rand and ken as arguments for the owners. Then if you want to find out the name and age of the owner of car2, you can access the following properties:


car2.owner.name  //  "Ken Jones"
car2.owner.age   //  39
NOTE: A major drawback of this approach is that you lose the type information on property owner of type car -- only the comment in the constructor informs you that the property is of type person. This is a dire consequence of JavaScript's weak typing.

You can add properties to a previously defined object. For example, the statement:

car1.color = "black"
adds the property color to object car1, and assigns it a value of "black." However, this does not affect any other car objects. To add this new property to all objects of the same type, you have to add the property to the definition of the car object type itself (that is, to its constructor, not just one of its objects).

Indexing Properties of Objects

In JavaScript 1.0, you can refer to an object's properties by their property name or by their ordinal index. In JavaScript 1.1 or later, however, if you initially define a property by its name, you can only refer to it by its name, and if you initially define a property by an index, you can only refer to it by its index.

This applies when you create an object with a constructor, as in the above example of the car object type, and when you define individual properties explicitly (for example, myCar.color = "red"). So if you define object properties initially with an index, such as myCar[5] = "25 mpg", you can only refer to the property as myCar[5].

The exception to this rule is objects reflected from HTML, such as the forms array. You can always refer to objects in these arrays by either their ordinal number (based on their sequential appearance in the document) or by their name (if defined). For example, if the first <FORM> tag in a document has a NAME attribute of "myForm", you can refer to the form as document.forms[0] or as document.forms["myForm"] or even as document.myForm.

Adding Object Type Properties via prototype

You can also add a property to a previously defined object type by using the prototype property of the Function object. This defines the current object type itself as a template of all its properties. The following code adds a color property to all objects of type car, and then assigns a value to the color property of the object car1:

car.prototype.color = null; // initially no value
car1.color = "black";

Associating Methods with Objects

A method is a function associated with an object. You define a method the same way you define any standard function. Then you use the following syntax to associate that function with an existing object:

object.methodName = functionName

where object is an existing object to get property methodName added, and functionName is the name of the existing function to associate with this object.
NOTE: This is exactly like assigning an event-handler to an event-handler name, or assigning the address of a function to a function pointer in C/C++.

You can then call the method in the context of the object as follows:

object.methodname( arguments )
You can also define methods for an object type this same way, by including a function-name assignment to a local method-name in the object type's constructor function. For example, you could define a function that would format and display the properties of the previously-defined car objects:

function displayCar()
{
     var result  =  "A Beautiful " + this.year + " " + 
                    this.make + " " + this.model;
     PrettyPrint( result );
}
where PrettyPrint() is function to display a horizontal line and a string. Notice the now-required use of this to refer back to the current object associated with this method.

As before, you then make this function a method of car by adding the assignment:

this.displayCar = displayCar;
to the constructor defining object type car. So the full definition of car would now be:

function car( mk, mdl, yr, ownr )
{
     make = mk;
     model = mdl;
     year = yr;
     owner = ownr;
     color = null;
     showCar = displayCar;
}
Then you can call the displayCar() method on each of the objects as follows:

car1.displayCar()
car2.displayCar()
This produces the output shown in the following figure.

Figure 7.1   Displaying method output

Using this for Object References

JavaScript has a reserved identifier -- this -- that you must use in a method to refer to the current object's properties. For example, suppose you have a function called validate() that validates an object's value property, given the object and the bounding values:


function validate( obj, lowval, hival )
{
     if( obj.value < lowval  ||  obj.value > hival )
       alert( "Invalid Value!" );
}
Then you could call validate() in each form element's onChange event-handler, using this to pass it the form element itself, as in the following example:


<INPUT TYPE="text" NAME="age" SIZE=3 onChange="validate(this,18,99)">
In general, this refers to the calling object in a method.

When combined with the FORM property, this can refer to the current document. In the following example, the form named myForm contains a Text object and a button. When the user clicks the button, the value of the Text object is set to the form's name. The button's onClick event-handler uses this to refer to the document containing the form, so that this.form will refer to myForm:


<FORM NAME="myForm"> 
   <INPUT TYPE="text" NAME="text1" VALUE="Beluga">
   <P>
<INPUT NAME="button1" TYPE="button" VALUE="Show Form Name"     onClick="this.form.text1.value=this.form.name"> </FORM>

Deleting Objects

You can remove an object by using the delete operator. The following code shows this:


myobj = new Number() // first create a Number object,
delete myobj   // then remove it and return true
For more information on delete, consult the Client-Side JavaScript Reference (page 57).

JavaScript 1.1. You can also remove an object by setting its object reference to null (if that is the last reference to the object). JavaScript finalizes the object immediately, as part of the assignment expression.

JavaScript 1.0. You cannot remove objects -- they exist until you leave the page containing the object.


Pre-defined Core Objects

This section describes the pre-defined objects in core JavaScript: Array, Boolean, Date, Function, Math, Number, RegExp, and String. The pre-defined client-side objects are described in Chapter 11, "Using Navigator Objects."

Array Object

JavaScript does not have an explicit array data-type. However, you can use the pre-defined Array object and its methods to work with arrays in your applications. The Array object has methods for manipulating arrays in various ways, such as joining, reversing, and sorting them. It has a property for determining the array length and other properties for use with regular expressions.

An array is an ordered set of values that you refer to with a name and an index. For example, you could have an array called emp that contains employees' names indexed by their employee number. So emp[1] would be employee number one, emp[2] employee number two, and so on.

Creating an Array

To create an Array object:

1. arrayObjectName = new Array(element0, element1, ..., elementN)
2. arrayObjectName = new Array(arrayLength)
arrayObjectName is either the name of a new object or a property of an existing object. When using Array properties and methods, arrayObjectName is either the name of an existing Array object or a proper ty of an existing object.

element0, element1, ..., elementN is a list of values for the array's elements. When this form is specified, the array is initialized with the specified values as its elements, and the array's length property is set to the number of arguments.

arrayLength is the initial length of the array. The following code creates an array of five elements:

billingMethod = new Array(5)
Array literals are also Array objects; for example, the following literal is an Array object. See "Array Literals" on page 37 for details on array literals.

coffees = ["French Roast", "Columbian", "Kona"]

Populating an Array

You can populate an array by assigning values to its elements. For example,

emp[1] = "Casey Jones"
emp[2] = "Phil Lesh"
emp[3] = "August West"
You can also populate an array when you create it:

myArray = new Array("Hello", myVar, 3.14159)

Referring to Array Elements

You refer to an array's elements by using the element's ordinal number. For example, suppose you define the following array:

myArray = new Array("Wind","Rain","Fire")
You then refer to the first element of the array as myArray[0] and the second element of the array as myArray[1].

The index of the elements begins with zero (0), but the length of array (for example, myArray.length) reflects the number of elements in the array.

Array Methods

The Array object has the following methods:

For example, suppose you define the following array:

myArray = new Array("Wind","Rain","Fire")
myArray.join() returns "Wind,Rain,Fire"; myArray.reverse transposes the array so that myArray[0] is "Fire", myArray[1] is "Rain", and myArray[2] is "Wind". myArray.sort sorts th e array so that myArray[0] is "Fire", myArray[1] is "Rain", and myArray[2] is "Wind".

Two-Dimensional Arrays

The following code creates a two-dimensional array.

a = new Array(4)
for (i=0; i < 4; i++) {
   a[i] = new Array(4)
   for (j=0; j < 4; j++) {
      a[i][j] = "["+i+","+j+"]"
   }
}
The following code displays the array:

for (i=0; i < 4; i++) {
   str = "Row "+i+":"
   for (j=0; j < 4; j++) {
      str += a[i][j]
   }
   document.write(str, "<p>")
}
This example displays the following results:

Row 0:[0,0][0,1][0,2][0,3]
Row 1:[1,0][1,1][1,2][1,3]
Row 2:[2,0][2,1][2,2][2,3]
Row 3:[3,0][3,1][3,2][3,3]

Arrays and Regular Expressions

When an array is the result of a match between a regular expression and a string, the array returns properties and elements that provide information about the match. An array is the return value of regexp.exec, string.match, and string.replace. For information on using arrays with regular expressions, see Chapter 4, "Regular Expressions."

Boolean Object

The Boolean object is a wrapper around the primitive Boolean data type. Use the following syntax to create a Boolean object:

booleanObjectName = new Boolean(value)
Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. Any object whose value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement. See "if...else Statement" on page 80 for more information.

Date Object

JavaScript does not have a date data type. However, you can use the Date object and its methods to work with dates and times in your applications. The Date object has a large number of methods for setting, getting, and manipulati ng dates. It does not have any properties.

JavaScript handles dates similarly to Java. The two languages have many of the same date methods, and both languages store dates as the number of milliseconds since January 1, 1970, 00:00:00.

The Date object range is -100,000,000 days to 100,000,000 days relative to 01 January, 1970 UTC.

To create a Date object:

dateObjectName = new Date([parameters])
where dateObjectName is the name of the Date object being created; it can be a new object or a property of an existing object.

The parameters in the preceding syntax can be any of the following:

JavaScript 1.2 and earlier versions. The Date object behaves as follows:

Methods of the Date Object

The Date object methods for handling dates and times fall into these broad categories:

With the "get" and "set" methods you can get and set seconds, minutes, hours, day of the month, day of the week, months, and years separately. There is a getDay method that returns the day of the week, but no corresponding setDay method, because the day of the week is set automatically. These methods use integers to represent these values as follows:

For example, suppose you define the following date:

Xmas95 = new Date("December 25, 1995")
Then Xmas95.getMonth() returns 11, and Xmas95.getFullYear() returns 95.

The getTime and setTime methods are useful for comparing dates. The getTime method returns the number of milliseconds since January 1, 1970, 00:00:00 for a Date object.

For example, the following code displays the number of days left in the current year:

today = new Date()
endYear = new Date(1995,11,31,23,59,59,999) // Set day and month
endYear.setFullYear(today.getFullYear()) // Set year to this year
msPerDay = 24 * 60 * 60 * 1000 // Number of milliseconds per day
daysL eft = (endYear.getTime() - today.getTime()) / msPerDay
daysLeft = Math.round(daysLeft) //returns days left in the year
This example creates a Date object named today that contains today's date. It then creates a Date object named endYear and sets the year to the current year. Then, using the number of milliseconds per da y, it computes the number of days between today and endYear, using getTime and rounding to a whole number of days.

The parse method is useful for assigning values from date strings to existing Date objects. For example, the following code uses parse and setTime to assign a date value to the IPOdate objec t:

IPOdate = new Date()
IPOdate.setTime(Date.parse("Aug 9, 1995"))

Using the Date Object: an Example

In the following example, the function JSClock() returns the time in the format of a digital clock.

function JSClock() {
   var time = new Date()
   var hour = time.getHours()
   var minute = time.getMinutes()
   var second = time.getSeconds()
  & nbsp;var temp = "" + ((hour > 12) ? hour - 12 : hour)
   temp += ((minute < 10) ? ":0" : ":") + minute
   temp += ((second < 10) ? ":0" : ":") + second
   temp += (hour >= 12) ? " P.M." : " A.M."
   return temp
}
The JSClock function first creates a new Date object called time; since no arguments are given, time is created with the current date and time. Then calls to the getHours, getMinutes, and getSeconds methods assign the value of the current hour, minute and seconds to hour, minute, and second.

The next four statements build a string value based on the time. The first statement creates a variable temp, assigning it a value using a conditional expression; if hour is greater than 12, (hour - 13), otherwise si mply hour.

The next statement appends a minute value to temp. If the value of minute is less than 10, the conditional expression adds a string with a preceding zero; otherwise it adds a string with a demarcating colon. Then a s tatement appends a seconds value to temp in the same way.

Finally, a conditional expression appends "PM" to temp if hour is 12 or greater; otherwise, it appends "AM" to temp.

Function Object

The pre-defined Function object specifies a string of JavaScript code to be compiled as a function.

To create a Function object:

functionObjectName = new Function ([arg1, arg2, ... argn], functionBody)
functionObjectName is the name of a variable or a property of an existing object. It can also be an object followed by a lowercase event handler name, such as window.onerror.

arg1, arg2, ... argn are arguments to be used by the function as formal argument names. Each must be a string that corresponds to a valid JavaScript identifier; for example "x" or "theForm".

functionBody is a string specifying the JavaScript code to be compiled as the function body.

Function objects are evaluated each time they are used. This is less efficient than declaring a function and calling it within your code, because declared functions are compiled.

In addition to defining functions as described here, you can also use the function statement. See the Client-Side JavaScript Reference for more information.

The following code assigns a function to the variable setBGColor. This function sets the current document's background color.

var setBGColor = new Function("document.bgColor='antiquewhite'")
To call the Function object, you can specify the variable name as if it were a function. The following code executes the function specified by the setBGColor variable:

var colorChoice="antiquewhite"
if (colorChoice=="antiquewhite") {setBGColor()}
You can assign the function to an event handler in either of the following ways:

1. document.form1.colorButton.onclick=setBGColor
2. <INPUT NAME="colorButton" TYPE="button"
      VALUE="Change background color"
     & nbsp;onClick="setBGColor()">
Creating the variable setBGColor shown above is similar to declaring the following function:

function setBGColor() {
   document.bgColor='antiquewhite'
}
You can nest a function within a function. The nested (inner) function is private to its containing (outer) function:

Math Object

The pre-defined Math object has properties and methods for mathematical constants and functions. For example, the Math object's PI property has the value of pi (3.141...), which you would use in an application as

Math.PI
Similarly, standard mathematical functions are methods of Math. These include trigonometric, logarithmic, exponential, and other functions. For example, if you want to use the trigonometric function sine, you would write

Math.sin(1.56)
Note that all trigonometric methods of Math take arguments in radians.

The following table summarizes the Math object's methods.

Table 7.1 Methods of Math
Method Description
abs

Absolute value

sin, cos, tan

Standard trigonometric functions; argument in radians

acos, asin, atan

Inverse trigonometric functions; return values in radians

exp, log

Exponential and natural logarithm, base e

ceil

Returns least integer greater than or equal to argument

floor

Returns greatest integer less than or equal to argument

min, max

Returns greater or lesser (respectively) of two arguments

pow

Exponential; first argument is base, second is exponent

round

Rounds argument to nearest integer

sqrt

Square root

Unlike many other objects, you never create a Math object of your own. You always use the pre-defined Math object.

It is often convenient to use the with statement when a section of code uses several math constants and methods, so you don't have to type "Math" repeatedly. For example,

with (Math) {
   a = PI * r*r
   y = r*sin(theta)
   x = r*cos(theta)
}

Number Object

The Number object has properties for numerical constants, such as maximum value, not-a-number, and infinity. You cannot change the values of these properties and you use them as follows:

biggestNum = Number.MAX_VALUE
smallestNum = Number.MIN_VALUE
infiniteNum = Number.POSITIVE_INFINITY
negInfiniteNum = Number.NEGATIVE_INFINITY
notANum = Number.NaN
You always refer to a property of the pre-defined Number object as shown above, and not as a property of a Number object you create yourself.

The following table summarizes the Number object's properties.

Table 7.2 Properties of Number
Method Description
MAX_VALUE

The largest representable number

MIN_VALUE

The smallest representable number

NaN

Special "not a number" value

NEGATIVE_INFINITY

Special infinite value; returned on overflow

POSITIVE_INFINITY

Special negative infinite value; returned on overflow

RegExp Object

The RegExp object lets you work with regular expressions. It is described in Chapter 4, "Regular Expressions."

String Object

The String object is a wrapper around the string primitive data type. Do not confuse a string literal with the String object. For example, the following code creates the string literal s1 and also the String object s2:

s1 = "foo" //creates a string literal value
s2 = new String("foo") //creates a String object
You can call any of the methods of the String object on a string literal value--JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the String.length property with a string literal.

You should use string literals unless you specifically need to use a String object, because String objects can have counterintuitive behavior. For example:

s1 = "2 + 2" //creates a string literal value
s2 = new String("2 + 2")//creates a String object
eval(s1) //returns the number 4
eval(s2) //returns the string "2 + 2"
A String object has one property, length, that indicates the number of characters in the string. For example, the following code assigns x the value 13, because "Hello, World!" has 13 characters:

myString = "Hello, World!"
x = mystring.length
A String object has two types of methods: those that return a variation on the string itself, such as substring and toUpperCase, and those that return an HTML-formatted version of the string, such as bold and link.

For example, using the previous example, both mystring.toUpperCase() and "hello, world!".toUpperCase() return the string "HELLO, WORLD!".

The substring method takes two arguments and returns a subset of the string between the two arguments. Using the previous example, mystring.substring(4, 9) returns the string "o, Wo." See the substring method of the String object in the Client-Side JavaScript Reference for more information.

The String object also has a number of methods for automatic HTML formatting, such as bold to create boldface text and link to create a hyperlink. For example, you could create a hyperlink to a hypothetical URL with the link method as follows:

mystring.link("http://www.helloworld.com")
The following table summarizes the methods of String objects.

Table 7.3 Methods of String
Method Description
anchor

Creates HTML named anchor

big, blink, bold,
fixed, italics, small,
strike, sub, sup

Creates HTML formatted string

charAt, charCodeAt

Returns the character or character code at the specified position in string

indexOf, lastIndexOf

Returns the position of specified substring in the string or last position of specified substring, respectively

link

Creates HTML hyperlink

concat

Combines the text of two strings and returns a new string

fromCharCode

Constructs a string from the specified sequence of ISO-Latin-1 codeset values

split

Splits a String object into an array of strings by separating the string into substrings

slice

Extracts a section of an string and returns a new string.

substring, substr

Returns the specified subset of the string, either by specifying the start and end indexes or the start index and a length

match, replace, search

Used to work with regular expressions

toLowerCase, toUpperCase

Returns the string in all lowercase or all uppercase, respectively


Home Page | Previous | Next

Last Updated: 05/27/99 21:21:27

Copyright (c) 1999 Netscape Communications Corporation