objectName.propertyNameBoth the object name and property name are case sensitive. You define a property by assigning it a value. For example, suppose there is an object named
myCar
(for now, just assume the object already exists). You can give it properties named make
, model
, and year
as follows:
myCar.make = "Ford"An array is an ordered set of values associated with a single variable name. Properties and arrays in JavaScript are intimately related; in fact, they are different interfaces to the same data structure. So, for example, you could access the properties of the
myCar.model = "Mustang"
myCar.year = 69;
myCar
object as follows:
myCar["make"] = "Ford"This type of array is known as an associative array, because each index element is also associated with a string value. To illustrate how this works, the following function displays the properties of the object when you pass the object and the object's name as arguments to the function:
myCar["model"] = "Mustang"
myCar["year"] = 67
function show_props(obj, obj_name) {So, the function call
var result = ""
for (var i in obj)
result += obj_name + "." + i + " = " + obj[i] + "\n"
return result
}
show_props(myCar, "myCar")
would return the following:
myCar.make = Ford
myCar.model = Mustang
myCar.year = 67
function
keyword, followed by
In Navigator JavaScript, it is good practice to define all your functions in the HEAD of a page so that when a user loads the page, the functions are loaded first.
For example, here is the definition of a simple function named pretty_print
:
function pretty_print(str) {This function takes a string,
document.write("<HR><P>" + str)
}
str
, as its argument, adds some HTML tags to it using the concatenation operator (+), and then displays the result to the current document using the write
method.
In addition to defining functions as described here, you can also define Function
objects, as described in "Function Object".
Using Functions
In a Navigator application, you can use (or call) any function defined in the current page. You can also use functions defined by other named windows or frames; for more information, see Chapter 4, "Using Windows and Frames." In a server-side JavaScript application, you can use any function compiled with the application.
Defining a function does not execute it. You have to call the function for it to do its work. For example, if you defined the example function pretty_print
in the HEAD of the document, you could call it as follows:
<SCRIPT>
The arguments of a function are not limited to strings and numbers. You can pass whole objects to a function, too. The
pretty_print("This is some text to display")
</SCRIPT>show_props
function (defined in "Objects and Properties") is an example of a function that takes an object as an argument.
A function can even be recursive, that is, it can call itself. For example, here is a function that computes factorials:
function factorial(n) {
You could then display the factorials of one through five as follows:
if ((n == 0) || (n == 1))
return 1
else {
result = (n * factorial(n-1) )
return result
}
}for (x = 0; x < 5; x++) {
The results are:
0 factorial is 1
document.write("<BR>", x, " factorial is ", factorial(x))
}
1 factorial is 1
2 factorial is 2
3 factorial is 6
4 factorial is 24
5 factorial is 120
Using the arguments Array
The arguments of a function are maintained in an array. Within a function, you can address the parameters passed to it as follows:
functionName.arguments[i]
where functionName
is the name of the function and i
is the ordinal number of the argument, starting at zero. So, the first argument passed to a function named myfunc
would be myfunc.arguments[0]
. The total number of arguments is indicated by the variable arguments.length
.
Using the arguments
array, you can call a function with more arguments than it is formally declared to accept using. This is often useful if you don't know in advance how many arguments will be passed to the function. You can use arguments.length
to determine the number of arguments actually passed to the function, and then treat each argument using the arguments
array.
For example, consider a function defined to create HTML lists. The only formal argument for the function is a string that is "U" for an unordered (bulleted) list or "O" for an ordered (numbered) list. The function is defined as follows:
function list(type) {
You can pass any number of arguments to this function, and it will then display each argument as an item in the indicated type of list. For example, the following call to the function
document.write("<" + type + "L>") // begin list
// iterate through arguments
for (var i = 1; i < list.arguments.length; i++)
document.write("<LI>" + list.arguments[i])
document.write("</" + type + "L>") // end list
}list("o", "one", 1967, "three", "etc., etc...")
results in this output:
1. one
2. 1967
3. three
4. etc., etc...
In JavaScript 1.2, arguments
includes additional properties, as described in the JavaScript Reference.
Creating New Objects
Both client-side and server-side JavaScript have a number of predefined objects. In addition, you can create your own objects. In JavaScript 1.2, if you only want one instance of an object, you can create it using an object initializer. Alternatively, if you want to be able to create multiple instances of an object, you can first create a constructor function and then instantiate an object using that function and the new
operator.
Using Object Initializers
In earlier versions of Navigator, you could create objects only using their constructor functions or using a function supplied by some other object for that purpose, as discussed in "Using a Constructor Function".
NOTE: In What's New in JavaScript 1.2, using object initializers was referred to as creating objects with literal notation. It was decided that the phrase "literal notation" could be misleading. "Object initializer" is consistent with the terminology used by C++.The syntax for an object using an object initializer is:
objectName = {property1:value1, property2:value2,..., propertyN:valueN}where
objectName
is the name of the new object, each property
I
is an identifier (either a name, a number, or a string literal), and each value
I
is an expression whose value is assigned to the property
I
. The objectName
and assignment is optional. If you do not need to refer to this object elsewhere, you do not need to assign it to a variable.
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 initializer used in a function is created each time the function is called.
Assume you have the following statement:
if (cond) x = {hi:"there"}In this case, JavaScript creates object and assigns it to the variable
x
if and only if the expression cond
is true.
The following example creates myHonda
with three properties. Note that the engine
property is also an object with its own properties.
myHonda = {color:"red",wheels:4,engine:{cylinders:4,size:2.2}}As discussed in Chapter 11, "Predefined Core Objects and Functions," JavaScript provides array objects. In Navigator 4.0, you can also use an initializer to create an array. The syntax for creating an array in this way is slightly different from creating other objects:
arrayName = [element0, element1, ..., elementN]
where arrayName
is the name of the new array and each element
I
is a value for on of the array's elements. When you create an array using an initializer, it is initialized with the specified values as its elements, and its length is set to the number of arguments. As with other objects, assigning the array to a variable name is optional.
You do not have to specify all elements in the new array. If you put 2 commas in a row, the array is created with spaces for the unspecified elements, as shown in the second example below.
If an array is created using an initializer in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array initializer. In addition, an initializer used in a function is created each time the function is called.
The following example creates the coffees
array with three elements and a length of three:
coffees = ["French Roast", "Columbian", "Kona"]
The following example creates the fish
array, giving values to two elements and having one empty element:
fish = ["Lion", , "Surgeon"]
With this expression fish[0]
is "Lion", fish[2]
is "Surgeon", and fish[1]
is undefined.
Using a Constructor Function
Alternatively, you can create your own object with these two steps:
car
, and you want it to have properties for make, model, year, and color. To do this, you would write the following function:
function car(make, model, year) {Notice the use of
this.make = make
this.model = model
this.year = year
}
this
to assign values to the object's properties based on the values passed to the function.
Now you can create an object called mycar
as follows:
mycar = new car("Eagle", "Talon TSi", 1993)This statement creates
mycar
and assigns it the specified values for its properties. Then the value of mycar.make
is the string "Eagle", mycar.year
is the integer 1993, and so on.
You can create any number of car
objects by calls to new
. For example,
kenscar = new car("Nissan", "300ZX", 1992)An object can have a property that is itself another object. For example, suppose you define an object called
vpgscar = new car("Mazda", "Miata", 1990)
person
as follows:
function person(name, age, sex) {and then instantiate two new
this.name = name
this.age = age
this.sex = sex
}
person
objects as follows:
rand = new person("Rand McKinnon", 33, "M")Then you can rewrite the definition of
ken = new person("Ken Jones", 39, "M")
car
to include an owner
property that takes a person
object, as follows:
function car(make, model, year, owner) {To instantiate the new objects, you then use the following:
this.make = make
this.model = model
this.year = year
this.owner = owner
}
car1 = new car("Eagle", "Talon TSi", 1993, rand)Notice that instead of passing a literal string or integer value when creating the new objects, the above statements pass the objects
car2 = new car("Nissan", "300ZX", 1992, ken)
rand
and ken
as the arguments for the owners. Then if you want to find out the name of the owner of car2, you can access the following property:
car2.owner.nameNote that you can always add a property to a previously defined object. For example, the statement
car1.color = "black"adds a property
color
to car1, and assigns it a value of "black." However, this does not affect any other objects. To add the new property to all objects of the same type, you have to add the property to the definition of the car
object type.
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 subsequently 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 objects in these arrays by either their ordinal number (based on where they appear in the document) or their name (if defined). For example, if the second <FORM>
tag in a document has a NAME
attribute of "myForm", you can refer to the form as document.forms[1]
or document.forms["myForm"]
or document.myForm
.
prototype
property. This defines a property that is shared by all objects of the specified type, rather than by just one instance of the object. 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.
For more information, see the prototype
property of the Function
object in the JavaScript Reference.
Car.prototype.color=null
car1.color="black"
birthday.description="The day you were born" Defining Methods
A method is a function associated with an object. You define a method the same way you define a standard function. Then you use the following syntax to associate the function with an existing object:
object.methodname = function_name
where object
is an existing object, methodname
is the name you are assigning to the method, and function_name
is the name of the function.
You can then call the method in the context of the object as follows:
object.methodname(params);
You can define methods for an object type by including a method definition in the object constructor function. For example, you could define a function that would format and display the properties of the previously-defined car
objects; for example,
function displayCar() {
where
var result = "A Beautiful " + this.year + " " + this.make
+ " " + this.model
pretty_print(result)
}pretty_print
is the function (defined in "Functions") to display a horizontal rule and a string. Notice the use of this
to refer to the object to which the method belongs.
You can make this function a method of car
by adding the statement
this.displayCar = displayCar;
to the object definition. So, the full definition of car
would now look like
function car(make, model, year, owner) {
Then you can call the
this.make = make
this.model = model
this.year = year
this.owner = owner
this.displayCar = displayCar
}displayCar
method for each of the objects as follows:
car1.displayCar()
This produces the output shown in Figure 10.1
car2.displayCar()
Figure 10.1 Displaying method output
Using this for Object References
JavaScript has a special keyword, this
, that you can use within a method to refer to the current object. For example, suppose you have a function called validate
that validates an object's value
property, given the object and the high and low values:
function validate(obj, lowval, hival) {
Then, you could call
if ((obj.value < lowval) || (obj.value > hival))
alert("Invalid Value!")
}validate
in each form element's onChange
event handler, using this
to pass it the form element, as in the following example:
<INPUT TYPE="text" NAME="age" SIZE=3
In general,
onChange="validate(this, 18, 99)">this
refers to the calling object in a method.
When combined with the form
property, this
can refer to the current object's parent form. In the following example, the form 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.form
to refer to the parent form, myForm
.
<FORM NAME="myForm">
Form name:<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> Object Deletion
In JavaScript for Navigator 2.0, you cannot remove objects--they exist until you leave the page containing the object. In JavaScript for Navigator 3.0, you can 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.
Last Updated: 11/26/97 09:25:56