Last Updated:

JavaScript Classes and Objects

The JavaScript scripting language is object-oriented. JavaScript objects are sets of properties and methods. Object properties are the data associated with an object, and methods are functions for processing the object's data.

You can address properties in JavaScript either by property names or by property number. The latter is possible due to the fact that all the properties of the object are stored as elements of the array and therefore each property has its own number.

 

Three Types of JavaScript Objects

 

JavaScript has three types of objects: embedded objects, browser objects, and objects that the programmer creates himself. Each of these types has its own purpose and its own characteristics.

Built-in objects

The following are built-in objects whose properties and methods are available in JavaScript without first defining those objects.

ObjectDescription
ArrayArray
BooleanLogical data
DateCalendar date
FunctionFunction
GlobalGlobal Methods
MathMathematical constants and functions
NumberNumber
ObjectObject
StringLine

Built-in objects are useful for performing various operations on strings, calendar dates, arrays, numbers, and so on. They free the programmer from performing various routine operations such as converting strings or calculating mathematical functions.

How do I work with embedded objects? Simple enough. The program creates implementations of the objects and then accesses the properties and methods of the objects. As a practical example, consider an HTML document that displays the current date and time.

Code Listing 2.1.

<HTML>
   <HEAD>
     <TITLE>Current date and time</TITLE>
   </HEAD>
   <BODY BGCOLOR=WHITE>
     <H1>Current date and time</H1>
     <SCRIPT LANGUAGE="JavaScript">
     <!--

       vardt;
       var szDate="";

       dt = new Date();
       szDate = "Date: " + dt.getDate() + "."
         + dt.getMonth() + "." + dt.getYear();

       document.write(szDate);
       document.write("<BR>");
       document.write("Time: " + dt.getHours()
         + ":" + dt.getMinutes() + ":" + dt.getSeconds());

     // -->
     </SCRIPT>
   </BODY>
</HTML>

Here, the JavaScript creates a Data object using the new keyword, and a Date constructor with no parameters:

var dt;
dt = new Date();

The Data object created in this way is initialized with the current local date set for the user (not on the Web server from which the corresponding HTML document was downloaded). The following line generates a text string for the date:

szDate = "Date: " + dt.getDate() + "."
  + dt.getMonth() + "." + dt.getYear();

The value of the calendar number, month number, and year is obtained here using the getDate, getMonth, and getYear methods, respectively. These methods are called on the dt object that contains the current date.

The date text string is output to the HTML document using the write method defined in the document object:

document.write(szDate);

The Date object also contains information about the current time. This information is retrieved for display using the getHours, getMinutes, and getSeconds methods (hours, minutes, and seconds, respectively): View an example of how this script works

document.write("Time: " + dt.getHours() 
  + ":" + dt.getMinutes() + ":" + dt.getSeconds());

 

Browser Objects

From the perspective of JavaScript, the browser appears to be a hierarchically organized set of objects. By accessing the properties and methods of these objects, you can perform various operations on a browser window loaded into that window by an HTML document, as well as on individual objects that are placed in an HTML document. For example, you can create new browser windows by loading HTML documents into them, dynamically generate html document text, access form fields defined in an HTML document, and so on.

Browser objects are the interface by which JavaScript interacts with the user and the HTML document loaded in the browser window, as well as with the browser itself. In JavaScript, you cannot create new classes based on the classes that correspond to these objects, but the properties and methods of browser objects are available.

Hierarchy of browser objects

The figure schematically shows the hierarchy of browser objects.

script

The window object is at the root of the hierarchy. When an HTML document is loaded into the browser window, other objects are created inside this object - documentparentframelocation and top.

If you load an HTML document with frames into a browser window, a separate window is created for each frame, and this window is created as a window object.

The document object contains other objects whose composition is entirely defined by the HTML document loaded into the browser window. These can be forms, links to other HTML documents or local links within the same document, objects that define the URL of the document, and so on.

If there are forms in the document, they are also represented as a hierarchical set of objects. A form object can contain objects such as buttons, radio buttons, and fields for entering text information.

By accessing the properties of the objects listed above, JavaScript can determine various characteristics of the HTML document, such as the title. It has access to all links placed in the document, as well as the contents of the form fields defined in the HTML document.

Object-related events

Each browser object is associated with a specific set of events that can be handled in JavaScript.

For example, the onLoad and onUnload events are associated with the window object. The first of these events occurs when the browser finishes loading the window and all the frames in it (if those frames are defined in the window). The second event occurs when the user exits the document by closing the browser window or switching to another document.

JavaScript can, for example, display a welcome message to the user or request additional information when handling the onLoad event. When a window is terminated (when the onUnload event is raised), the script can release any resources associated with the window or display a message on the monitor screen.

 

Objects based on classes created by the programmer

JavaScript uses a different approach to creating your own classes than many programming languages. A JavaScript class is created as a function that defines properties that play the role of data. Methods are also defined as functions, but separately.

Here's a concrete example. Suppose you want to create a class that is designed to store a record of an imaginary telephone database. In this class, you need to provide properties for storing the name, surname, phone number, address, as well as a special feature for records that are closed from unauthorized access. In addition, you must develop methods that are designed to display the contents of an object in tabular form.

First of all, let's create our own class called myRecord. Let there be no methods in it until there are methods, we will add them later. The search class is created as follows:

function myRecord(name, family, phone, address)
{
  this.name    = name;
  this.family  = family;
  this.phone   = phone;
  this.address = address;
  this.secure  = false;
}

It is easy to see that the description of this class is nothing more than a function of the constructor.

Constructor options are for setting the properties of an object when it is created from a class. Properties are defined by simple references to their names with the this keyword. This keyword here specifies that the operator references the properties of the object for which the constructor is called, that is, the object being created.

Notice that the constructor initializes a property named secure, writing false to it. The corresponding parameter is not provided in the constructor, which is quite acceptable.

How do I use a specific class? From this class, you can create an arbitrary number of objects. The following is a javascript snippet where two objects, rec1 and rec2, are created from the myRecord class:

var rec1;
var rec2;
rec1 = new myRecord("Ivan", "Ivanov",
   "000-322-223", "Malaya Bolshaya st., 225, apt. 226");
rec2 = new myRecord("Peter", "Petrov",
   "001-223-3334", "Bolshaya Malaya st., 552, apt. 662");
rec2.secure = true;

Objects are created using the new operator. Parameters are passed to the constructor to initialize the properties of the created objects.

As for the property named secure, in the rec2 object it is initialized after the latter is created. It is set to true. The secure property of the rec1 object is not changed, so it stores false.

Now let's add new methods named printTableHead, printTableEnd, and printRecord to the defined class. The first two of these methods output the start and end portion of the table to the HTML document, respectively, and the third displays the table rows that reflect the contents of the records. In abbreviated form, the new definition of the myRecord class is presented below:

function printTableHead()
{
  . . .
}
function printTableEnd()
{
  . . .
}
function printRecord()
{
  . . .
}
function myRecord(name, family, phone, address)
{
  this.name    = name;
  this.family  = family;
  this.phone   = phone;
  this.address = address;
  this.secure  = false;
  this.printRecord    = printRecord;
  this.printTableHead = printTableHead;
  this.printTableEnd  = printTableEnd;
}

Here, before defining the constructor, are the definitions for the method functions of our class. In addition, a definition of new properties has been added to the constructor: These properties store references to the methods defined above. After such a class definition, you can create objects and access certain methods: Here is the full source code of the resulting program.

this.printRecord    = printRecord;
this.printTableHead = printTableHead;
this.printTableEnd  = printTableEnd;
rec1.printTableHead();
rec1.printRecord();
rec1.printTableEnd();
rec2.printTableHead();
rec2.printRecord();
rec2.printTableEnd();

Code Listing 2.2.

<HTML>
  <HEAD>
    <TITLE>View entries</TITLE>
    <SCRIPT LANGUAGE="JavaScript">
    <!--

    function printTableHead()
    {
      var szSec = "";
      if(this.secure)
        szSec = "(Secure)";
      else
        szSec = " (Unsecure)".fontcolor("red");

      document.write("<TABLE BORDER>");
      document.write("<CAPTION ALIGN=LEFT>" +
        this.name + " " + this.family + szSec +
        "</CAPTION>");
      document.write("<TH ALIGN=LEFT>Write field</TH>"
        + "<TH ALIGN=LEFT>Content</TH>");
    }

    function printTableEnd()
    {
      document.write("</TABLE>");
      document.write("<P>");
    }

    function printRecord()
    {
      document.write("<TR><TD>Name:</TD><TD>" +
        this.name.italics() + "</TD></TR>");
      document.write("<TR><TD>Family:</TD><TD>" +
        this.family.italics() + "</TD></TR>");
      document.write("<TR><TD>Phone:</TD><TD>" +
        this.phone.italics() + "</TD></TR>");
      document.write("<TR><TD>Address:</TD><TD>" +
        this.address.italics() + "</TD></TR>");
    }

    function myRecord(name, family, phone, address)
    {
      this.name = name;
      this.family = family;
      this phone = phone;
      this address = address;
      this.secure = false;
      this.printRecord = printRecord;
      this.printTableHead = printTableHead;
      this.printTableEnd = printTableEnd;
    }

    // -->
    </SCRIPT>
  </HEAD>
  <BODY BGCOLOR=WHITE>
    <H1>View Posts</H1>
    <SCRIPT LANGUAGE="JavaScript">
    <!--

    varrec1;
    varrec2;

    rec1 = new myRecord("Ivan", "Ivanov",
      "000-322-223", "Malaya Bolshaya st., 225, apt. 226");

    rec2 = new myRecord("Peter", "Petrov",
      "001-223-3334", "Bolshaya Malaya st., 552, apt. 662");
    rec2.secure = true;

    rec1.printTableHead();
    rec1.printRecord();
    rec1.printTableEnd();

    rec2.printTableHead();
    rec2.printRecord();
    rec2.printTableEnd();

    // -->
    </SCRIPT>
  </BODY>
</HTML>

The definition of the new myRecord class and its methods is located in the header area of the HTML document, as is customary.

The printTableHead method prints the table header to the HTML document. The appearance of this header depends on the contents of the object's properties. First, the printTableHead method checks the secure property by retrieving its value using the this keyword:

var szSec = "";
if(this.secure)
  szSec = " (Secure)";
else
  szSec = " (Unsecure)".fontcolor("red");

Here, this keyword means that you must use a property of the object on which the printTableHead method was called. If the contents of the secure property are true, the string "(Secure)" is written to the szSec text variable. If it is false, the string "(Unsecure)" is entered into this variable, and the string is set to red.

Because in JavaScript all text strings (including literals) are objects of the built-in String class, you can call the methods defined in this class on them. Specifically, the fontcolor method allows you to set the color of the string.

Next, the printTableHead method prints a <TABLE statement to the HTML document> with a BORDER parameter that begins the definition of a table that has a frame. The label above the table is specified using the dynamically generated <CAPTION> statement. This label includes the first and last name extracted from the corresponding properties of the object on which the printTableHead method was called. This method then displays labels for the columns in the table.

The printTableEnd method outputs the </TABLE statement to the HTML document> that completes the definition of the table, as well as an empty paragraph to separate the tables that follow each other:

function printTableEnd()
{
  document.write("</TABLE>");
  document.write("<P> ");
}

The last method defined in the class is called printRecord. It prints the contents of the first four properties of the object as a table row defined in the HTML document by the printTableHead function just described. Notice that the contents of the object's properties are printed in a slanted font, for which we call the italics method:

document.write("<TR><TD>Name:</TD><TD>" +   
  this.name.italics() + "</TD></TR>");

The second part of the script, located in the body of the HTML document, creates two objects, rec1 and rec2, based on the myRecord class, and then sets the secure property of the rec2 object to true.

Next, the script sequentially outputs two tables to the HTML document that correspond to the created objects by calling the printTableHead, printRecord, and printTableEnd methods.

As you can see, the use of its own class made it possible to greatly simplify the task of initializing and displaying the contents of the records of an imaginary telephone database. In fact, this task is reduced to calls to several methods defined in advance in our class.