O'Reilly logo

VBScript in a Nutshell, 2nd Edition by Ron Petrusha, Matt Childs, Paul Lomax

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

Initialize Event

Syntax

Sub object_Initialize(  )

Description

Use the Initialize event of a class defined with the Class...End Class construct to prepare the object or class for use, setting any references to subobjects or assigning default values to properties and values to class-level variables.

Rules at a Glance

  • The Initialize event is triggered automatically when a class is first instantiated by the Set statement. For example, in the following code, the Set statement generates the Initialize event:

    Dim MyObject As MyClass
    'some code
    ...
    'initialize event called here
    Set MyObject = New MyClass
    StrName = MyObject.CustName
  • The Initialize event doesn’t take any arguments.

  • It is best to declare the Initialize event as Private, although this is not required.

Programming Tips and Gotchas

  • While it’s possible to explicitly call the Initialize event from within the object at any stage after the object has been created, it isn’t recommended, because the code in the Initialize event should be written to be “run once” code.

  • Use the Initialize event of a class module to generate references to dependent objects. For example:

    Option Explicit Dim custOrder Set custOrder = New Order ' ...other code Class Order Private cust, itemsOrdered Private Sub Class_Initialize() Set cust = New Customer Set itemsOrdered = New Items End Sub End Class Class Customer ' Implementation of Customer End Class Class Items Dim orderItem(10) Private Sub Class_Initialize() Set orderItem(0) = New Item End Sub ' Other implementation ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required