Object-Oriented Programming with VBScript (1)
As I recently wrote, VBScript supports Object-Oriented Programming. However, we have to get used to certain limitations.
Let’s start with an example of a corner stone principle – encapsulation.
Class declaration example
Class Point2D '' Properties Private p_X Private p_Y '---------------------- '' Methods 'Constructor - called automatically Private Sub Class_Initialize() X = 0 Y = 0 End Sub '---------------------- 'Destructor - called automatically Private Sub Class_Terminate() End Sub '---------------------- 'A pair of methods to access private property X Property Get X X = p_X End Property Property Let X(ByVal in_X) p_X = in_X End Property '---------------------- 'A pair of methods to access private property Y Property Get Y Y = p_Y End Property Property Let Y(ByVal in_Y) p_Y = in_Y End Property '---------------------- End Class
As you can see, Point2D class I defined, has two private properties. To access the properties outside of the class, I defined a pair of special methods (Property Let, Property Get). Note: Property Get method can not accept parameters, and Property Let method can accept multiple parameters. Read more about it in Microsoft VBScript online help.
Here’s how we use a new class.
Public Sub Test1() Dim P Dim V1 Set P = new Point2D ' At this point, class constructor was called and executed V1 = P.X 'At this point, Property Get method was called and executed P.Y = 10 'At this point, Property Let method was called and executed Set P = Nothing ' At this point, class destructor was called and executed End Sub
Now about some disadvantages (or inconveniences).
Class declaration is Private
Classes, you declare in one code module, are unknown for other ones. That is, if Point2D class is declared in Point.vbs file, in Line.vbs file we can not create an instance of Point2D object with new operator.
Instead, in Point.vbs module we need to define a function that returns the instance.
Public Function NewPoint2D(ByVal in_X, ByVal in_Y) Dim P Set P = new Point2D P.X = in_X P.Y = in_Y Set NewPoint2D = P End Function
Do not to forget to declare this function as Public.
No Class Inheritance
Yep, in VBScript there is no inheritance mechanism.
Luckily, we have a workaround technique, called Delegation. Read more with code examples.
No Polymorphism
Although built-in VBScript functions DO allow parameter variation and defaulting, we can not define polymorphic functions in our custom code.
There are few workarounds to address this problem. They are all based on complex data types (array, record). I prefer using Dictionary object.