Chapter: Internet & World Wide Web HOW TO PROGRAM - VBScript

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Classes and Objects - VBScript

In this section, we introduce the concepts (i.e., “object think”) and the terminology (i.e., “ob-ject speak”) of object-oriented programming in VBScript.

Classes and Objects


In this section, we introduce the concepts (i.e., “object think”) and the terminology (i.e., “ob-ject speak”) of object-oriented programming in VBScript. Objects encapsulate (i.e., wrap to-gether) data (attributes) and methods (behaviors); the data and methods of an object are intimately related. Objects have the property of information hiding. This phrase means that, although objects may communicate with one another, objects do not know how other objects are implemented—implementation details are hidden within the objects themselves. Surely it is possible to drive a car effectively without knowing the details of how engines and transmis-sions work. Information hiding is crucial to good software engineering.


In VBScript, the unit of object-oriented programming is the Class from which objects are instantiated (i.e., created). Methods are VBScript procedures that are encapsu-lated with the data they process within the “walls” of classes.


VBScript programmers can create their own user-defined types called classes. Classes are also referred to as programmer-defined types. Each class contains data as well as the set of methods which manipulate that data. The data components of a class are called instance variables. Just as an instance of a variant is called a variable, an instance of a class is called an object. The focus of attention in object-oriented programming with VBScript is on classes rather than methods.


The nouns in a system-requirements document help the VBScript programmer deter-mine an initial set of classes with which to begin the design process. These classes are then used to instantiate objects that will work together to implement the system. The verbs in a system-requirements document help the VBScript programmer determine what methods to associate with each class.


This section explains how to create and use objects, a subject we call object-based pro-gramming (OBP).VBScript programmers craft new classes and reuse existing classes. Soft-ware is then constructed by combining new classes with existing, well-defined, carefully tested, well-documented, widely available components. This kind of software reusability speeds the development of powerful, high-quality software. Rapid applications develop-ment (RAD) is of great interest today.


Early versions of VBScript did not allow programmers to create their own classes, but VBScript programmers can now indeed develop their own classes, a powerful capability also offered by such object-oriented languages as C++ and Java.


Packaging software as classes out of which we make objects makes more significant portions of major software systems reusable. On the Windows platform, these classes have been packaged into class libraries, such as Microsoft’s MFC (Microsoft Foundation Classes) that provide C++ programmers with reusable components for handling common programming tasks, such as the creating and manipulating of graphical user interfaces.

Objects are endowed with the capabilities to do everything they need to do. For example, employee objects are endowed with a behavior to pay themselves. Video game objects are endowed with the ability to draw themselves on the screen. This is like a car being endowed with the ability to “go faster” (if someone presses the accelerator pedal), “go slower” (if someone presses the brake pedal) and “turn left” or “turn right” (if someone turns the steering wheel in the appropriate direction). The blueprint for a car is like a class. Each car is like an instance of a class. Each car comes equipped with all the behaviors it needs, such as “go faster,” “go slower” and so on, just as every instance of a class comes equipped with each of the behaviors instances of that class exhibit. We will discuss how to create classes and how to add properties and methods to those classes.


Classes normally hide their implementation details from the clients (i.e., users) of the classes. This is called information hiding. As an example of information hiding, let us con-sider a data structure called a stack.


Think of a stack in terms of a pile of dishes. When a dish is placed on the pile, it is always placed at the top (referred to as pushing the dish onto the stack). When a dish is removed from the pile, it is always removed from the top (referred to as popping the dish off the stack). Stacks are known as last-in, first-out (LIFO) data structures—the last item pushed (inserted) on the stack is the first item popped (removed) from the stack. So if we push 1, then 2, then 3 onto a stack, the next three pop operations will return 3, then 2, then 1.


The programmer may create a stack class and hide from its clients the implementation of the stack. Stacks can be implemented with arrays and other techniques such as linked lists. A client of a stack class need not know how the stack is implemented. The client simply requires that when data items are placed in the stack with push operations, they will be recalled with pop operations in last-in, first-out order. Describing an object in terms of behaviors without concern for how those behaviors are actually implemented is called data abstraction, and VBScript classes define abstract data types (ADTs). Although users may happen to know how a class is implemented, users should not write code that depends on these details. This allows a class to be replaced with another version without affecting the rest of the system, as long as the Public interface of that class does not change (i.e. every method still has the same name, return type and parameter list in the new class definition).

Most programming languages emphasize actions. In these languages, data exists in support of the actions programs need to take. Data is “less interesting” than actions, anyway. Data is “crude.” There are only a few built-in data types, and it is difficult for pro-grammers to create their own new data types. VBScript elevates the importance of data. A primary activity in VBScript is creating new data types (i.e., classes) and expressing the interactions among objects of those classes.


An ADT actually captures two notions, a data representation of the ADT and the oper-ations allowed on the data of the ADT. For example, subtype integer defines addition, sub-traction, multiplication, division and other operations in VBScript, but division by zero is undefined. The allowed operations and the data representation of negative integers are clear, but the operation of taking the square root of a negative integer is undefined.

Access to Private data should be carefully controlled by the class’s methods. For example, to allow clients to read the value of Private data, the class can provide a get method (also called an accessor method or a query method).


To enable clients to modify Private data, the class can provide a set method (also called a mutator method). Such modification would seem to violate the notion of Private data. But a set method can provide data validation capabilities (such as range checking) to ensure that the data is set properly and to reject attempts to set data to invalid values. A set method can also translate between the form of the data used in the interface and the form used in the implementation. A get method need not expose the data in “raw” format; rather, the get method can edit the data and limit the view of the data the client will see.

Classes often provide Public methods to allow clients of the class to set (i.e., assign values to) or get (i.e., obtain the values of) Private instance variables. These methods are special methods in VBScript called Property Let, Property Set and Prop-erty Get (collectively these methods and the internal class data they manipulate are called properties). More specifically, a method that sets variable mInterestRate would be named Property Let InterestRate and a method that gets the InterestRate would be called Property Get InterestRate.


Procedures Property Let and Property Set differ in that Property Let is used for non-object subtypes (e.g., integer, string, byte, etc.) and Property Set is used for object subtypes.


A Property Let Hour that stores the hour in universal time as 0 to 23 is shown in Fig. 24.21. Notice the change in the declaration of variable mHour—we are using keyword Private rather than Dim. In this case, Private restricts the scope of mHour to its class. If Dim or Public is used, the variable is accessible outside the class. Method definitions that are not preceded by Public or Private default to Public. Variables declared with Dim default to Public.


Suppose Property Let Hour is a member of class CTime1 (we discuss how to create classes momentarily). An object of class CTime1 is created with the following code


Dim wakeUp

Set wakeUp = New CTime1




Private mHour


    Public Property Let Hour( hr )

    If hr >= 0 And hr < 24 Then

    mHour = hr


    mHour = 0

   End If

   End Property

                Fig. 24.21  Simple Property Let procedure.


When creating an object, VBScript keyword New is used and followed by the class name. When assigning the object to a variable, keyword Set must be used. When a variable (e.g., wakeUp) refers to an object, the variable is called a reference.

If we perform the assignments wakeup.Hour = -6 or wakeup.Hour = 27, the Property Let procedure would reject these as invalid values and set theHour to 0. The Property Get Hour procedure is shown in Fig. 24.22.


Using CTime1 class object wakeUp, we can store the value of Hour into variable alarmClockHourValue, as follows:


alarmClockHourValue = wakeup.Hour


which call Property Get Hour to get the value of theHour. The Class definition for CTime1 is shown in Fig. 24.23. Keywords Class and End Class encapsulate the class members.


    Public Property Get Hour()

    Hour = mHour

End Property


Fig. 24.22  Simple Property Get procedure.


    Class CTime1

    Private mHour


    Public Property Let Hour( hr )

    If hr >= 0 And hr < 24 Then

    mHour = hr


    mHour = 0

    End If

      End Property

      Public Property Get Hour()

      Hour = mHour

      End Property

      End Class


Fig. 24.23  Simple Class definition.


Suppose we have a CEmployee class that references a CDate object named mBirthDate. We cannot use a Property Let to assign a value to an object. Instead, we must use a Property Set, as in each of the following Property procedures:


Public Property Set BirthDay(bDay)

Set mBirthDate = bDay

End Property


Public Property Get BirthDay()

Set BirthDay = mBirthDate

End Property


Any Property Get, Property Let or Property Set method may contain the


Exit Property statement that causes an immediate exit from a Property procedure. Accessor methods can read or display data. Another common use for access methods is to test the truth or falsity of conditions—such methods are often called predicate


methods. An example of a predicate method would be an IsEmpty method for any con-tainer class—a class capable of holding multiple objects—such as a linked list or a stack. A program might test IsEmpty before attempting to remove another item from a container object. A program might test IsFull before attempting to insert another item into a con-tainer object.


It would seem that providing set and get capabilities is essentially the same as making the instance variables Public. This is another subtlety of VBScript that makes the lan-guage desirable for software engineering. If an instance variable is Public, it may be read or written at will by any method in the program. If an instance variable is Private, a Public get method certainly seems to allow other methods to read the data at will but the get method controls the formatting and display of the data. A Public set method can— and most likely will—carefully scrutinize attempts to modify the instance variable’s value. This ensures that the new value is appropriate for that data item. For example, an attempt to set the day of the month to 37 would be rejected, an attempt to set a person’s weight to a negative value would be rejected, and so on.

Figure 24.24 demonstrates using a VBScript Class. The Web page allows the user to enter a first name, age and social security number which are displayed in a message dialog. This example briefly introduces a VBScript feature for complex pattern matching called regular expressions. We use regular expressions to validate the format of the social security number. Client-side scripts often validate information before sending it to the server. In this example, we briefly introduce regular expressions in the context of client-side validation. In Chapter 27, Perl, you will learn more about regular expressions.


Lines 16–69 define Class Person, which encapsulates Private data members, Public Property procedures and a Private method. Data members store the person’s first name in name, the person’s age in yearsOld and the person’s social secu-rity number in ssn. Both Property Let and Property Get procedures are provided for the data members.


          <?xml version = "1.0"?>

          <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"



          <!--Fig. 24.24: classes.html -->

          <!-- VBScript Class       -->


          <html xmlns = "">


          <title>Using a VBScript Class</title>


          <script type = "text/vbscript">


          Option Explicit


          Class Person

          Private name, yearsOld, ssn


          Public Property Let FirstName( fn )

          name = fn

          End Property


          Public Property Get FirstName()

          FirstName = name

          End Property


          Public Property Let Age( a )

          yearsOld = a

          End Property


          Public Property Get Age()

          Age = yearsOld

          End Property


          Public Property Let SocialSecurityNumber( n )


          If Validate( n ) Then

          ssn = n


          ssn = "000-00-0000"

          Call MsgBox( "Invalid Social Security Format" )

          End If


          End Property


Public Property Get SocialSecurityNumber()

SocialSecurityNumber = ssn

End Property      


Private Function Validate( expression )

Dim regularExpression

Set regularExpression = New RegExp


regularExpression.Pattern = "^\d{3}-\d{2}-\d{4}$"


If regularExpression.Test( expression ) Then

          Validate = True   


          Validate = False  

End If        


End Function      


Public Function ToString()

ToString = name & Space( 3 ) & age & Space( 3 ) _

          & ssn

End Function      


End Class   ' Person      


Sub cmdButton_OnClick()     

Dim p                   ' Declare object reference

Set p = New Person       ' Instantiate Person object


With p       

.FirstName = Document.Forms(0).txtBox1.Value

.Age = CInt( Document.Forms(0).txtBox2.Value )

.SocialSecurityNumber =_


Call MsgBox( .ToString() )

End With   


End Sub              







          <form action = "">Enter first name

          <input type = "text" name = "txtBox1" size = "10" />

          <p>Enter age

          <input type = "text" name = "txtBox2" size = "5" /></p>

          <p>Enter social security number

          <input type = "text" name = "txtBox3" size = "10" />


          <input type = "button" name = "cmdButton"

          value = "Enter" /></p>




Fig. 24.24  Using VBScript classes and regular expressions


Procedure Property Let SocialSecurityNumber (lines 35–44) is the most interesting Property procedure because it calls Private method Validate to verify the correct format for the social security number that was input. If Validate returns True, the social security number input is assigned to ssn; if Validate returns False, ssn is assigned the string "000-00-0000" and a message dialog is displayed.


Method Validate (line 50–62) checks the format of the social security number by using a so-called regular expression—a concept we explain in the next paragraph. Methods designated as Private are often called utility or helper methods. These methods are con-sidered to be part of a class’s implementation detail and therefore clients do not have access to them.

The statement in line 52 instantiates a regular expression object (i.e., an object of VBScript class RegExp) and assigns it to reference regularExpression. Line 54 sets the Pattern property to the pattern we wish to match—in this case a social security number which consists of three digits, a hyphen (i.e., -), two digits, a hyphen and four digits. This expression reads as follows: the beginning of the string should begin with exactly three digits followed by a hyphen, then two digits followed by a hyphen and end with exactly four digits. The caret, ^ indicates the beginning of the string and the \d indi-cates that any digit (i.e., 0–9) is a match. The {3}, {2} and {4} expressions indicate that exactly three occurrences of any digit, exactly two occurrences of any digit and exactly four occurrences of any digit, respectively, are a match. The dollar sign, $ indicates the end of the string. The hyphens are treated as literal characters (i.e., a hyphen is not a special char-acter used in a regular expression for pattern matching—so a hyphen literally is treated as a hyphen).


The If’s condition (line 56) calls function Test to determine whether the regular expression’s pattern is a match for the string passed into Test. A successful match returns True and an unsuccessful match returns False. For more details on VBScript regular expressions, visit



Function ToString (line 64) returns a string containing the name, age and ssn. Function Space (line 65) is called to provide three spaces between words. Keywords End Class (line 69) designate the end of the class definition.

Lines 71–83 provide an event procedure for cmdButton’s OnClick event. Line 72 declares p as a variant—which can store object subtypes. The statement in line 73 instan-tiates a Person object and assigns it to p. As mentioned earlier, VBScript requires the use of the Set keyword when assigning an object to a variable. To be more precise, we call p a reference, because it is used with an object. At any moment in time, a reference can refer to an object or Nothing (i.e., a special value that indicates the absence of an object).


Lines 75–81 use the With/End With statement to set several property values for p and to call p’s ToString method. The With/End With statement is provided for the convenience of the programmer, to minimize the number of times an object’s name is written (when setting multiple properties or calling multiple methods). Note that lines 76– 79 actually call the appropriate Property Let procedures—these lines are not directly accessing p’s data. Line 80 calls p’s ToString method to get the string that the message dialog will display. Although the syntax may appear a bit strange, it is indeed correct.


Operator Precedence Chart


This section contains the operator precedence chart for VBScript (Fig. 24.25). Operators are shown in decreasing order of precedence from top to bottom.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Copyright © 2018-2020; All Rights Reserved. Developed by Therithal info, Chennai.