Richard G Baldwin (512) 223-4758, baldwin@austin.cc.tx.us, http://www.austin.cc.tx.us/baldwin/

JavaScript Programming, Objects and Properties

 

Java/Web Programming, Lecture Notes # 2140, Revised 05/25/98.


Preface

The material was prepared as part of a new tutorial that I plan to publish on Web programming in general.  It is not part of the Java academic curriculum at ACC.

The purpose of this series of lessons is to teach you how to program in JavaScript.  The goal is to provide a programming tutorial that will be accessible to persons with no programming experience and will be equally useful to persons who already have programming experience using JavaScript or some other language.
 

Introduction

According to Netscape:
 
JavaScript is based on a simple object-oriented paradigm. An object is a construct with properties that are JavaScript variables or other objects. An object also has functions associated with it that are known as the object's methods. In addition to objects that are predefined in the Navigator client and the server, you can define your own objects. 
 
This lesson provides information on how to create and use properties.
 

Properties in JavaScript

An object has state and behavior.  In JavaScript, the state of an object is stored in its properties.  Object properties in JavaScript are variables or other objects that are associated with the object.
 

Direct Access to Properties

JavaScript allows you to directly access the values of the properties of an object using the following syntax:
 
 
objectName.propertyName
 
According to the pure Netscape definition of a property, all properties are exposed and accessible according to the syntax shown above.

However, taking some liberties and applying concepts that are common in other areas of OOP, I will say that in some cases, the value of a property cannot be accessed directly by referring to the name of the property as above.  This is often the case when the value of the property is not stored directly but needs to be calculated from raw data at the time that you need it.  In this case, you refer to a method of the object that performs the desired calculation and delivers the requested value.  Again, this is not a true property according to the Netscape definition, but rather mimics what experts in other areas of OOP consider to be a property.

We will see examples of both types of property access in the next sample script.  An example of referring to a property access method is shown below.
 
 
objectName.methodName()
 
JavaScript is a case-sensitive language, and this applies to the names of objects, properties, and methods.  For example, an object named theObj is not the same object as one named TheObj.

Unlike other OOP languages, you can add new properties to existing objects in JavaScript.  This is illustrated in the following sample script that first instantiates an object of the predefined object type Date and then adds a new property to that object. The property that is added is a true property according to the Netscape definition of a property.

The script instantiates a new object named dateObject by applying the new operator to one form of the Date constructor.  The form of the constructor that was used creates a new object containing the date and time that the object was constructed.  This is illustrated by the following code fragment (other forms of the constructor are available as well). 
 

      dateObject = new Date();
 
Although this object has only one true property named prototype (which we aren't interested in at this time), it can deliver a number of calculated properties having to do with date and time when its methods are invoked.  In addition, we will add a new property having to do with my name using the syntax shown in the following fragment.  You can always use this syntax to add new properties to an existing object.  This syntax adds the new property only to this one object.  It is also possible to add a new property to all objects of a given type.  We will learn how to do this in a subsequent lesson.

We will access several of these properties later for display purposes. 
 

      dateObject.myName = "Dick Baldwin";
 
This predefined object can deliver calculated properties for month, year, hour, minute, etc., but it doesn't actually store all of those items as separate entities.  Rather, it stores the number of milliseconds since January 1, 1970.  Then, when you ask for the month, it uses a method to calculate the month and deliver it to you.  Therefore, to access these calculated properties, you need to access the methods shown in the following code fragment.

In this fragment, we access five different methods on the object, such as getMonth(), which return the requested information.  We then assign that information to a variable that will be displayed later.

Note that all of the information is returned from the methods in numeric form.  For example, January is represented by the numeric value 0, February is represented by 1, etc.  To make the results more consistent with what we are accustomed to, we add one to the value returned for the month so that January will be represented by 1 instead of 0 (as in 1/16/98 instead of 0/16/98 for January 16, 1998). 
 

      theMonth = dateObject.getMonth() + 1;      
      theDay = dateObject.getDate();
      theYear = dateObject.getYear();
      theHour = dateObject.getHours();
      theMin = dateObject.getMinutes();
 
Finally, we access our new true property named myName as shown in the following fragment.  In this case, access to the property is embedded in the argument list of a call to the write() method so that the property value is written into the HTML document for display on the screen. Note that this statement uses the access method for true properties provided early in this lesson. 
 

      document.write("My name is " + dateObject.myName + "<BR>");
 
In discussing these code fragments, we have included only those fragments most important to the subject at hand.  We have skipped over the other code necessary tie everything together.  The entire script showing everything in context appears below.  The output from running the script is shown in the comments at the beginning. 
 

<!-- File Js00000360.htm
Copyright 1998, R.G.Baldwin 
This script is designed to illustrate the fact that you can add
new properties to existing objects.

The output from running this script is:
Instantiate date object
Add new name property to the object
Display properties of date object
Date is 5/25/98
Time is 10:38
My name is Dick Baldwin

Done. 
-------------------------------------------------------------------->
<HTML>
  <HEAD> 
  </HEAD>

  <BODY>
    <SCRIPT LANGUAGE="JavaScript1.2">
      <!-- Hide script
      
      document.write("<BR>Instantiate date object<BR>");
      dateObject = new Date();
      document.write("Add new name property to the object<BR>");
      dateObject.myName = "Dick Baldwin";
      document.write("Display properties of date object<BR>");
      theMonth = dateObject.getMonth() + 1;      
      theDay = dateObject.getDate();
      theYear = dateObject.getYear();
      theHour = dateObject.getHours();
      theMin = dateObject.getMinutes();
      document.write("Date is " + theMonth + "/" + theDay + "/" 
                                                 + theYear + "<BR>");
      document.write("Time is " + theHour + ":" + theMin + "<BR>");
      document.write("My name is " + dateObject.myName + "<BR>");

      // End hiding  -->
    </SCRIPT>

    <P> Done.
  </BODY>
</HTML>
 
I hope that my discussion of true Netscape properties and calculated properties hasn't been too confusing to you.  However, I feel that in learning to write JavaScript code, you should also be exposed to the larger world outside of JavaScript so that when you decide to step out into that world, you won't be confined to thinking in the narrow terms of JavaScript.

Other object-oriented programming environments strongly discourage direct access to property values using the JavaScript syntax shown below. 
 

objectName.propertyName
 
Those programming environments strongly encourage that access to properties be restricted to the use of property access methods using syntax such as the following. 
 

objectName.accessMethodName()
 
In fact, the standard design pattern for a property in Java is that it is accessible using a method where the name of the method is as shown below. 
 

objectName.getPropertyName()
 
In the Java naming convention, PropertyName is the name of the property. Of course, if you have no plans to go beyond JavaScript, you need not be concerned with any of this.



Special for loop in Objects

During our earlier study of flow of control, we skipped over a special version of a for loop that is peculiar to objects because you didn't have the background to understand it at that time.  You now have the background, so we will introduce and use it here.

According to Netscape 
 

The for...in statement iterates a specified variable over all the properties of an object. For each distinct property, JavaScript executes the specified statements. A for...in statement looks as follows: 

for (variable in object) { 
   statements }

 
We will use this statement in the next sample script.  As a preview, the following fragment would display the names of all of the properties of an object named myObject..
 
for(var prop in myObject){
  document.write("prop = " + prop + "<BR>");
}//end for loop
.

Static Properties

JavaScript supports a concept that Netscape refers to as static properties.  The most important characteristic of a static property is the following.
 
If an object type has a static property, that property can be accessed without a requirement to instantiate an object of the type.  It can be accessed simply by joining the name of the object type to the name of the property with a period as illustrated below. 
 
In the following example, Math is the name of an object type and PI is the name of a static property of that object type. This expression would return the value of PI, presumably to be used in some larger overall expression.
 
Math.PI
 
The same concept is supported by other OOP languages such as Java where, in this example, PI would be referred to as a class variable of the class named Math.
 
 

Array Access to Properties

When we studied arrays, we learned that objects of the Array type can behave as an associative array.  In particular, we learned that if we store a string in an element of the array, we can then associate another variable or object with that string in the sense of a key-value pair.

Having done this, we can access the associated value using a reference of the following type:
 
myArray["keyName"]
 
In other words, a reference to the name of the array with the name of the key in square brackets will return the value associated with that key. (We demonstrated that this works not only for string keys, but for boolean and non-integer numeric keys as well.)

Properties in JavaScript appear to be stored in an associative array where the name of the object (or the name of the object type for the case of static properties) is the name of the array and the name of the property is the key.  The value of the property can then be accessed by referencing the object as though it were an associative array and providing the name of the property, in string format in square brackets, as the key.

The following statement will return the value of the static property named PI of the object type named Math. This is an alternative to joining the name of the object and the name of the property with a period as shown earlier.
 
Math[PI]
 
If this were not a static property, it would be necessary to use the name of an object instantiated from the object type instead of the name of the object type alone.

Note that while the object behaves as an array in some respects, it doesn't behave as an array in all respects.  For example, the following expression will not return a string representing the name of a property as would be the case if this were an ordinary Array object.
 
Math[0]
 
An attempt to perform array access on an object using a numeric index simply returns undefined.

The following sample script illustrates much of what we have been discussing above.  This script illustrates  how to "discover" and display the names and values of JavaScript object properties.

The script begins by instantiating a new array named myArray that will be used to save the names of all the properties of the Math object type.
 
      nameArray = new Array();
 
Then we use the special form of the for loop to obtain and save a list of the names of all the properties of the object.  This is the form of the for loop that we introduced above.  During each iteration, the variable named prop contains a string which is the name of the next property in the object.  The loop terminates after all properties have been examined.

Recall that an object of type Array automatically expands, as needed, to accommodate each new element that we store in the array.  In this case, we use the length property of the Array object to determine the index of the next new element in the array, and store the string naming the next property in a new element having that index. 
 

      for(var prop in Math){
        nameArray[nameArray.length] = prop;
      }//end for loop
 
At this point, we have an array containing one element for each property of the Math object type.  We use the information in this array to execute an ordinary for loop which

Note in particular the following expression which is a double-indexed operation.  I have added some extra spaces to make this more apparent.
 
Math[   nameArray[cnt]   ]
 
First we extract a string from nameArray at index cnt.  This string is the name of a property.  Then we use that string as an associative index into Math to access the value of the property.
 
      for(cnt = 0; cnt < nameArray.length; cnt++){
        document.write("Property name: " + nameArray[cnt] + "<BR>" 
          + "Property value: " + Math[nameArray[cnt]] +"<BR>");
      }//end for loop
 
This sample script also illustrates the ability to access the values of non-static properties by performing an associative access on the name of an object of type Math.  In this case, since the Math type doesn't have any non-static properties, I instantiated an object of type Math named myObj and added a property to the object named myName.  I assigned a string value to the property which was, in fact, my name.

I then used the name of the new property to access its value in two different ways:

In both cases, the value that was returned (my name) was passed as a parameter to the write() method where it was displayed on the screen.
 
      myObj = new Math();
      myObj.myName = "Dick Baldwin";
      document.write("Array style: "+ myObj["myName"] + "<BR>");
      document.write("Normal style: " + myObj.myName);
 
All of the code fragments discussed above can be viewed in context in the complete listing of the script which follows.  The comments at the beginning of the script show the output produced by the various calls to the write() method in the script.
 
<!-- File Js00000370.htm
Copyright 1998, R.G.Baldwin 
This script is designed to illustrate  how to "discover" and display
the names and values of JavaScript object properties.


The output from running this script is:
Get and save property names in an array
Use property names to access values
Property name: E
Property value: 2.718281828459045
Property name: LOG2E
Property value: 1.4426950408889634
Property name: LOG10E
Property value: .4342944819032518
Property name: LN2
Property value: .6931471805599453
Property name: LN10
Property value: 2.302585092994046
Property name: PI
Property value: 3.141592653589793
Property name: SQRT2
Property value: 1.4142135623730951
Property name: SQRT1_2
Property value: .7071067811865476

Instantiate an object of type Math, add a new
property to the object, and display the value of
the new property by referencing it both in
associative array style and "normal" style.

Array style: Dick Baldwin
Normal style: Dick Baldwin 

Done. 
-------------------------------------------------------------------->
<HTML>
  <HEAD> 
  </HEAD>

  <BODY>
    <SCRIPT LANGUAGE="JavaScript1.2">
      <!-- Hide script

      document.write("Get and save property names in an array<BR>");
      nameArray = new Array();

      for(var prop in Math){
        nameArray[nameArray.length] = prop;
      }//end for loop

      document.write("Use property names to access values<BR>");
      for(cnt = 0; cnt < nameArray.length; cnt++){
        document.write("Property name: " + nameArray[cnt] + "<BR>" 
          + "Property value: " + Math[nameArray[cnt]] +"<BR>");
      }//end for loop

      document.write(
        "<BR>Instantiate an object of type Math, add a new<BR>"
        + "property to the object, and display the value of<BR>"
        + "the new property by referencing it both in<BR>"
        + "associative array style and \"normal\" style.<BR><BR>");

      myObj = new Math();
      myObj.myName = "Dick Baldwin";
      document.write("Array style: "+ myObj["myName"] + "<BR>");
      document.write("Normal style: " + myObj.myName);

      // End hiding  -->
    </SCRIPT>

    <P> Done.
  </BODY>
</HTML>
 
-end-