在VBScript中使用類(一)
2024-07-21 02:15:28
供稿:網友
 
前言
首先,在我進入實質性主題并解釋如何建立類之前,我希望保證你知道“對象”。雖然你可以在程序中使用對象而不用知道其正確的規則,但我并不建議如此!對于對象的初學者,接下來的部分將讓你了解其概念及內容。已經了解面向對象編程(oop)的讀者可以跳過這章節。
 
導論
l “對象是什么?”——對象通常代表某種實體,主要是一個變量和函數的集合。
l “實體是什么?”——字面上說,實體是一個“事物”,我的意思是一個概念或者任何一個物體。例如,一輛汽車是一個實體,因為它是一個物體。你公司銷售部門銷售產品也是一個實體,當然,你也可以將其拆開來看,銷售人員、客戶、產品等都是實體。
 
讓我們更深入的來看“銷售”這個實體(對象)。為了使你更準確地有一個銷售的“映像”,你需要知道客戶買了什么,是哪個客戶,誰是銷售人員等等……這看來是一個簡單的事件,但假設所有信息是存儲在單獨的數據庫表中的,那么當你需要獲得某個銷售過程所有相關信息時,你必須在你的數據庫中做多次獨立查詢,再將所有的數據集攏。有沒有更簡便的辦法而一次獲得銷售的所有信息呢?“對象”。
 在對象中,你可以植入代碼以從其他表中獲得數據,你也可以保存對象屬性的所有信息,這樣,你可以輕松地使用代碼管理你的銷售數據。例如:
'open the database connection
set objconn = server.createobject("adodb.connection")
objconn.open "mydsn"
 
'create the recordset object
set objrs = server.createobject("adodb.recordset")
 
'define the sql query
strcomplexsqlquery = "select c.name, s.name from customers c, " & _
 "salespeople s, sales sl where sl.customerid=c.id and " & _
 "sl.salespersonid=s.id and sl.id=" & stridofthissale & ";"
 
'open the recordset
objrs.open strcomplexsqlquery, objconn, adopenforwardonly, _
 adlockreadonly, adcmdtext
 
'take the customer and sales person names from the recordset
strcustomername = objrs(0)
strsalespersonname = objrs(1)
 
'tidy up the objects
objrs.close
objconn.close
set objrs = nothing
set objconn = nothing
 
'output the data
response.write "this sale was made by " & strsalespersonname & _
 " to " & strcustomername
 
可以使用“對象”來替代:
'create the "sale" object
set objsale = new sale
 
'lookup the correct sale
objsale.id = stridofthissale
 
'output the data
response.write "this sale was made by " & objsale.salespersonname & _
 " to " & objsale.customername
 
'tidy up the objects
objsale.close
set objsale = nothing
如果你使用“sale”對象做比打印更多的事,可以讓你省去很多的打字時間。
 
 計算中,對象包括“屬性”和“方法”。屬性主要是儲存在對象中的一個變量,其用法與變量相同。唯一的區別在于參數賦值為:strmyvar = "this is a string variant", 而對象屬性為 objobject.property="this is a string variant"。這點非常簡單而有用處。方法可以理解為植入對象中的函數與過程,可以使用strmyvar = objobject.methodname(strmyvar)來代替strmyvar =functionname(strmyvar)。寫法不同,但功能相同。屬性的一個例子是對象response中的expireabsolute,response.expiresabsolute = cdate("1 september 1999")。方法的一個例子是對象response中的write方法,response.write "hello world!"。
 vbscript的一個新特性就是其可以創建新的對象而不需要求諸于花銷時間都極大的編譯器。我將向讀者展示如何創建對象的類,并希望提供一個良好的開端。
 
如果有什么問題歡迎來http://www.showc.com中討論
感謝sophie的翻譯