Objects and Classes
- Updated2024-09-12
- 2 minute(s) read
VBScript Language Directory > Objects and Classes
Objects and Classes
Objects contain properties and methods. Properties are like variables and methods are like functions and procedures. Use an object to combine data and functionality. Objects are always derived from a class and are generated at run time.
To make this easier to understand, imagine that an object is the virtual image of a real object. For example, you could have a class called Car that has properties like Brand, Transmission, and Color, and methods like Acceleration, Brake, Blink. The class is then a template from which objects can be generated. The object is the concrete instance of a class, for example, a blue Rolls Royce with an automatic transmission. Every object that this Car class generates receives a unique name. The object can read and write the properties, and can execute the methods.
A class is usually part of a library. We could have a library called Vehicles, with the classes, Car, Truck, Bus, and Motorcycle.
The following statements show how you can generate and use a CAR object.
Dim oMyCAr Set oMyCAR = CreateObject("vehicles.CAR") oMyCAR.Brand = "Rolls Royce" oMyCAR.Transmission = "Automatic" oMyCAR.Color = "Blue" Call oMyCAR.Accelerate
Use the Set statement to assign an object reference to a variable. Use the point operator to access properties and methods of an object. To change a property of an object, use a statement with the same structure as the following:
ObjectVar.Property = "XXX"
To execute a method of an object, use a statement with the same structure as the following:
Call ObjectVar.Method
The following example shows the same statements for the real class FileSystemObject that is part of a library which VBS uses to cooperate with your Windows file system. The example generates a FileSystemObject object and saves the object reference in the variable oFSO. Then the example uses the FileExists method of the object to test whether the file Autoexec.bat exists. A message box displays the result:
Dim oFSO, bExists Set oFSO = CreateObject("Scripting.FileSystemObject") bExists = oFSO.FileExists("C:\Autoexec.bat") Call MsgBox(bExists)