This section provides a tutorial example on how to define the Class_Initialize procedure to be called by the 'New' operator, and the Class_Terminate procedure to be called when the object lost its last reference.
To control how an object gets instantiated and terminated, we need to learn few more things:
1. "Class_Initialize" Subroutine Procedure - Initializes a new object.
The "Class_Initialize" procedure will be called whenever "New class_name" is used an expression.
You should declare the "Class_Initialize" procedure as "Private" to prevent any outside code calling it directly.
Here is the "Class_Initialize" procedure structure:
Private Sub Class_Initialize()
' initialize private variables
' initialize properties
End Class
2. "Class_Terminate" Subroutine Procedure - Clears a terminating object.
The "Class_Terminate" procedure will be called whenever the last reference of an object is removed.
You should declare the "Class_Initialize" procedure as "Private" to prevent any outside code calling it directly.
Here is the "Class_Terminate" procedure structure:
Private Sub Class_Terminate()
' remove storages used by private variables
' remove storates used by properties
End Class
2. "Nothing" Object - Releases the object reference of stored in the variable when assigned to a variable.
Here is how the "Nothing" object should be used:
Set variable_name = Nothing
Now I am ready to show you a VBScript example that uses Class_Initialize and Class_Terminate procedures:
<html><body>
<!-- Initialized_Class.html
- Copyright (c) 2015, HerongYang.com, All Rights Reserved.
-->
<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))
Set oEmpty = Nothing
' Checking the object again
document.writeln("VarType(oEmpty)=vbObject: " _
& (VarType(oEmpty)=vbObject))
document.writeln("TypeName(oEmpty): " & TypeName(oEmpty))
' Defining an empty class
Class EmptyClass
Sub Class_Initialize()
document.writeln("Initializing a object...")
End Sub
Sub Class_Terminate()
document.writeln("Terminating an object...")
End Sub
End Class
</script></pre>
</body></html>
When you load this example into IE, you will get a security warning.
You can ignore it and get the output:
Initializing a object...
VarType(oEmpty)=vbObject: True
TypeName(oEmpty): EmptyClass
Terminating an object...
VarType(oEmpty)=vbObject: True
TypeName(oEmpty): Nothing
Notice that:
"Set oEmpty = New EmptyClass" caused the Class_Initialize procedure executed while creating the new object.
"Set oEmpty = Nothing" caused the reference of the new object to be removed. Because this is the last reference,
the Class_Terminate procedure is called.