Creating Classes in VBScript
Creating
classes in VBScript is really no different than creating classes in any other
programming language. The concept of an
object is usually described as just about anything. When you think about it every thing around you
is some sort of object. For example a
house is an object. It has properties
and methods. The properties
could be that the house has 3 bedrooms, a garage, a pool, air conditioning
etc. You can even break down the house
into smaller objects, such as doors windows etc. A garage door may have methods that
are controlled by a remote. The methods
may be something like garageDoor.open or garageDoor.close. The garage door would be an object, and the method
would be to open or close. Getting back
to the VBScript, lets see how we would write a simple class called Math that
adds or subtracts two numbers. First
let’s look at our parameters for the class.
Class
Name: Math
Methods:
add and subtract
Now
before we actually create the class, lets just see how we would write the two
methods:
Public
Function add(afirst, asecond)
Dim output
output = afirst + asecond
add = output
End
Function
Public
Function subtract(sfirst, ssecond)
Dim output
output = sfirst - ssecond
subtract = output
End
Function
Now
we can define the class:
Class
Math
End
Class
Then
just put them together:
<%
Class Math
Public Function add(afirst, asecond)
Dim output
output = afirst + asecond
add = output
End
Function
Public
Function subtract(sfirst, ssecond)
Dim output
output = sfirst - ssecond
subtract = output
End
Function
End
Class
%>
Now
you can use your class in an include file to reduce code and increase
reusability. Go ahead and make a file
called Math.inc that has the above code in it.
When you have finished that, create a new .asp file called test.asp that
has this code.
PLEASE
NOTE: You
might need to change your parenthesis when you paste the code into the asp
file. By change I mean just re-write
them inside of the asp file.
<!--
#INCLUDE FILE="Math.inc" -->
<%
Dim mathObject
Dim additionResult
Dim subtractResult
Set mathObject = New Math
additionResult = mathObject.add(1,2)
subtractResult = mathObject.subtract(2,1)
Response.Write "result of addition:
" & additionResult & "<br>"
Response.Write "result of subtraction:
" & subtractResult & "<br>"
%>
The
first thing that we do in our code is to create 3 variables: mathObject,
additionResult, and subtractResult.
There is really nothing special about these variables. Next, we instantiate (or create an instance)
of the Math object with the line:
Set
mathObject = New Math
Next
we perform the method add, passing the parameters 1 and 2:
mathObject.add(1,2)
Since
add is a function that returns a value (as we defined in the class
specification) we store the returned value in the variable additionResult. Likewise, we use the same object, and perform
the subtraction method:
mathObject.subtract(2,1)
And
our result is stored in subtractionResult.
Then we simply print the variables out to the screen.
Visual
Basic defines what a property is differently than almost any other
language. If you read the document on
classes in VBA that is on the course web page, you will find that VB has what
look like property definitions. The Get/Let
property skeletons looks like this:
Public
Propetry Get <PropertyName>
End
Property
Public
Property Let <PropertyName>
End
Property
So
for our next example, we will use these properties to make a class called
Student. Here is what our code will look
like for the Student.inc file:
%
Class
Student
Private
name
Private
major
Private
classification
Public
Property Let studentName(inputName)
name = inputName
End
Property
Public
Property Let studentMajor(inputMajor)
major = inputMajor
End
Property
Public
Property Let studentClassification(inputClassification)
classification = inputClassification
End
Property
Public
Property Get studentName()
studentName = name
End
Property
Public
Property Get studentMajor()
studentMajor = major
End
Property
Public
Property Get studentClassification()
studentClassification = classification
End
Property
End
Class
%>
The
code is pretty simple. You can set the
student’s name, major, and classification and you can get the students name,
major, and classification as well. When
we make the variables private, this allows us only to call the Get methods to
get the values. So you basically cannot
directly access the variables when creating an instance of the Student
object. Now let’s put the code to use, create
a file named MakeStudent with the following code:
<!--
#INCLUDE FILE="Student.inc" -->
<%
Dim objStudent
Set objStudent = New Student
objStudent.studentName = "John Doe"
objStudent.studentMajor = "MIS"
objStudent.studentClassification =
"Undergraduate"
Response.Write objStudent.studentName
Response.Write "<br>"
Response.Write objStudent.studentMajor
Response.Write "<br>"
Response.Write
objStudent.studentClassification
%>
The
code itself is pretty self explanatory, but this example brings up a good
point. When you think about storing
information from your database, objects become very reasonable. Using objects is a good way to store specific
information about a given student. This
way you reduce your code, and the information is more abstract, thus making it
easier to manage. The last example shows
how we can create a form using objects.
This would be useful if you want to make a few forms on your html
page. For our example we will make one
form with a two text boxes and a button.
So first lets define some methods:
·
addTextBox(textboxName)
·
addButton(buttonValue)
·
createForm(formAction)
·
finishForm
Now
lets just go ahead and make the class:
<%
Class
Form
Public Sub createForm(formAction)
Response.Write "<form method=’post’
action=’" & formAction & "’>"
End Sub
Public Sub addTextBox(textboxName)
Response.Write "<br>"
Response.Write "<input type=’text’
name=’" & textboxName & "’ size=’20’>"
End Sub
Public Sub addButton(buttonValue)
Response.Write "<input
type=’submit’ value=’" & buttonValue & "’>"
End Sub
Public
Sub finishForm
Response.Write "</form>"
End
Sub
End
Class
%>
Copy
the code into a file called Form.inc, then make a file that will create a form
according to your specifications:
<!--
#INCLUDE FILE="Form.inc" -->
<%
Dim
formObject
Set
formObject = new Form
FormObject.createForm(“logon.asp”)
FormObject.addTextBox(“username”)
FormObject.addTextBox(“password”)
FormObject.addButton(“logon!”)
FormObject.finishForm
%>
Obviously
there are different ways you could construct your form. Using global variables and ‘set’ methods
would probably be better, so try constructing one using your own code that
incorporates the code above, and the ‘set’ methods and private global variables
from the previous example. An example of
this would be getting the form name via a Let Procedure. Here is a snippet of what I am talking about:
Private
formName
Public
Property Let FormName(strInputName)
formName = strInputName
End
Property
Public
Sub createForm(formAction)
Response.Write "<form name=’” &
formName & “’method=’post’ action=’" & formAction &
"’>"
End
Sub
What
I did was just added a private global variable that holds the name of the
form. The private global variable can be
accessed by all of the Properties and Subroutines. In order to set the name of the form you
could write something like this:
Dim
objForm
Set
objForm = New Form
objForm.FormName
= “Login Form”
objForm.createForm(“logon.asp”)
Class
TVProgram
Public StartTime
Public ProgramDate
Public ProgramTitle
End Class
Dim objTVShow
Set objTVShow = New TVProgram
objTVShow.StartTime =
CDate("17:30")
objTVShow.ProgramDate = DateSerial(1999,9,17)
objTVShow.ProgramTitle = "The
Jerry Springer Show"
Response.Write objTVShow.ProgramTitle
& " is on at " & _
objTVShow.StartTime & " on "
& objTVShow.ProgramDate
Class
TVProgram
Public StartTime
Public internal_ProgramDate
Public
Property Get ProgramDate
ProgramDate =
Day(internal_ProgramDate) & _
"
" & MonthName(Month(internal_ProgramDate)) & _
"
" & Year(internal_ProgramDate)
End Property
Public ProgramTitle
End Class
Dim objTVShow
Set objTVShow = New TVProgram
objTVShow.StartTime =
CDate("17:30")
objTVShow.internal_ProgramDate =
DateSerial(1999,9,17)
objTVShow.ProgramTitle = "The
Jerry Springer Show"
Response.Write objTVShow.ProgramTitle
& " is on at " & _
objTVShow.StartTime &
" on " & objTVShow.ProgramDate & "."
<html><body>
<!--
Empty_Class.html
Copyright (c) 2006 by Dr. Herong Yang.
http://www.herongyang.com/
-->
<pre><script
language="vbscript">
' Initiating an object from a class
Dim oEmpty
Set oEmpty = New EmptyClass
' Checking the object
document.writeln("VarType(oEmpty)=vbObject: " _
& (VarType(oEmpty)=vbObject))
document.writeln("TypeName(oEmpty):
" & TypeName(oEmpty))
'
Defining an empty class
Class
EmptyClass
End
Class
</script></pre>
</body></html>
Run
this VBScript example in IE, you will get:
VarType(oEmpty)=vbObject:
True
TypeName(oEmpty):
EmptyClass
Note
that "TypeNmae()" function returns the class name of the specified
object.
To
show you how to define public properties with property procedures, I wrote this
VBScript example:
<html><body>
<!--
Class_Methods.html
Copyright (c) 2006 by Dr. Herong Yang.
http://www.herongyang.com/
-->
<pre><script
language="vbscript">
Dim oNode
Set oNode = New Node
oNode.Email = "info@yahoo.com"
document.writeln()
document.writeln("Information of the
object:")
document.writeln(" oNode.Email: " & oNode.Email)
document.writeln(" oNode.ToString(): " &
oNode.ToString())
document.writeln(" oNode(): " & oNode())
document.writeln(" oNode: " & oNode)
Class
Node
Private User, Domain
Public Default Function ToString()
ToString = Email()
End Function
Public Property Let Email(sEmail)
at = InStr(sEmail, "@")
If at>0 Then
User = Mid(sEmail, 1, at-1)
Domain = Mid(sEmail, at+1, Len(sEmail)-at)
End If
End Property
Public Property Get Email()
Email = User & "@" &
Domain
End Property
Sub Class_Initialize()
User = "user"
Domain = "some.com"
End Sub
End
Class
</script></pre>
</body></html>
When
you load this VBScript example into IE, you will get this output:
Information
of the object:
oNode.Email: info@yahoo.com
oNode.ToString(): info@yahoo.com
oNode(): info@yahoo.com
oNode: info@yahoo.com
Notice
that how the default method can be invoked without method name, oNode() or
oNode.
No comments:
Post a Comment