VBScript Class Objects



Class is a construct that is used to define a unique type. Like Object Oriented Programming, VbScript 5.0 supports the creation of classes and it is very similar to writing COM objects with VB.

Class is simply the template for an object and we instantiate an object to access the properties and methods of it. Classes can contain variables, properties, methods or events.

Syntax

VBScript classes are enclosed within Class .... End Class

'Defining the Class
Class classname 'Declare the object name
...
End Class

' Instantiation of the Class
Set objectname = new classname

Class Variables

Classes can contain variables, which can be of private or public. Variables within classes should follow VBScript naming conventions. By default, the variables in class are Public. That is why they can be accessed outside the class.

Dim var1 , var2.
Private var1 , var2.
Public var1 , var2.

Class Properties

Class properties, such as Property Let, which handles the process of data validation and assigning the new value to the private variable. Property set, which assigns the new property value to the private object variable.

Read-only properties have only a Property Get procedure while write-only properties (which are rare) have only a Property Let or a Property Set procedure.

Example

In the below example, we are using Properties to wrap private variables.

Class Comp
   
   Private modStrType
   Private OS
 
   Public Property Let ComputerType(strType)
      modStrType = strType
   End Property
 
   Public Property Get ComputerType()
      ComputerType = modStrType
   End Property
 
   Public Property Set OperatingSystem(oObj)
      Set OS = oObj
   End Property
 
   Public Property Get OperatingSystem()
      Set OperatingSystem = OS
   End Property
 
End Class

Class Methods

Methods allow the class to perform the operation that the developer wants. The Methods are nothing but Functions or Subroutines.

Example

In the below example, we are using Properties to wrap private variables.

Class Car
   
   Private Model
   Private Year
 
   Public Start()
      Fuel = 2.45
	   Pressure =  4.15
   End Function
 
End Class

Class Events

There are two events that are automatically associated with every class by default. Class_Initialize and Class_Terminate.

Class_Initialize is triggered whenever you instantiate an object based on the class. Class_Terminate event is fired when the object goes out of scope or when the object is set to Nothing.

Example

In the below example, we will make you understand how the events work in VBScript.

'Instantation of the Object
Set objectname = New classname 
   
Private Sub Class_Initialize(  )
	Initalization code goes here
End Sub

'When Object is Set to Nothing
Private Sub Class_Terminate(  )
	Termination code goes here
End Sub
vbscript_object_oriented.htm
Advertisements