VBScript 類物件



類是一種用於定義唯一型別的構造。像面向物件程式設計一樣,VbScript 5.0 支援類的建立,它與使用 VB 編寫 COM 物件非常相似。

類僅僅是物件的模板,我們例項化一個物件來訪問它的屬性和方法。類可以包含變數、屬性、方法或事件。

語法

VBScript 類包含在Class .... End Class 之間

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

' Instantiation of the Class
Set objectname = new classname

類變數

類可以包含變數,這些變數可以是私有的或公共的。類中的變數應遵循 VBScript 命名約定。預設情況下,類中的變數是Public。因此,可以在類外部訪問它們。

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

類屬性

類屬性,例如 Property Let,它處理資料驗證和將新值賦給私有變數的過程。Property Set,它將新的屬性值賦給私有物件變數。

只讀屬性僅具有 Property Get 過程,而只寫屬性(很少見)僅具有 Property Let 或 Property Set 過程。

示例

在下面的示例中,我們使用屬性來包裝私有變數。

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 Car
   
   Private Model
   Private Year
 
   Public Start()
      Fuel = 2.45
	   Pressure =  4.15
   End Function
 
End Class

類事件

預設情況下,每個類都自動關聯兩個事件。Class_Initialize 和 Class_Terminate。

Class_Initialize 在您基於類例項化物件時觸發。Class_Terminate 事件在物件超出範圍或物件設定為 Nothing 時觸發。

示例

在下面的示例中,我們將幫助您瞭解事件在 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
廣告

© . All rights reserved.