在vbscript中使用類
前言
首先,在我進(jìn)入實(shí)質(zhì)性主題并解釋如何建立類之前,我希望保證你知道“對象”。雖然你可以在程序中使用對象而不用知道其正確的規(guī)則,但我并不建議如此!對于對象的初學(xué)者,接下來的部分將讓你了解其概念及內(nèi)容。已經(jīng)了解面向?qū)ο缶幊蹋╫op)的讀者可以跳過這章節(jié)。
導(dǎo)論
l “對象是什么?”——對象通常代表某種實(shí)體,主要是一個(gè)變量和函數(shù)的集合。
l “實(shí)體是什么?”——字面上說,實(shí)體是一個(gè)“事物”,我的意思是一個(gè)概念或者任何一個(gè)物體。例如,一輛汽車是一個(gè)實(shí)體,因?yàn)樗且粋€(gè)物體。你公司銷售部門銷售產(chǎn)品也是一個(gè)實(shí)體,當(dāng)然,你也可以將其拆開來看,銷售人員、客戶、產(chǎn)品等都是實(shí)體。
讓我們更深入的來看“銷售”這個(gè)實(shí)體(對象)。為了使你更準(zhǔn)確地有一個(gè)銷售的“映像”,你需要知道客戶買了什么,是哪個(gè)客戶,誰是銷售人員等等……這看來是一個(gè)簡單的事件,但假設(shè)所有信息是存儲在單獨(dú)的數(shù)據(jù)庫表中的,那么當(dāng)你需要獲得某個(gè)銷售過程所有相關(guān)信息時(shí),你必須在你的數(shù)據(jù)庫中做多次獨(dú)立查詢,再將所有的數(shù)據(jù)集攏。有沒有更簡便的辦法而一次獲得銷售的所有信息呢?“對象”。
在對象中,你可以植入代碼以從其他表中獲得數(shù)據(jù),你也可以保存對象屬性的所有信息,這樣,你可以輕松地使用代碼管理你的銷售數(shù)據(jù)。例如:
‘open the database connectionset objconn = server.createobject("adodb.connection")objconn.open "mydsn" ‘create the recordset objectset objrs = server.createobject("adodb.recordset") ‘define the sql querystrcomplexsqlquery = "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 recordsetobjrs.open strcomplexsqlquery, objconn, adopenforwardonly, _ adlockreadonly, adcmdtext ‘take the customer and sales person names from the recordsetstrcustomername = objrs(0)strsalespersonname = objrs(1) ‘tidy up the objectsobjrs.closeobjconn.closeset objrs = nothingset objconn = nothing ‘output the dataresponse.write "this sale was made by " & strsalespersonname & _ " to " & strcustomername
可以使用“對象”來替代:
‘create the "sale" objectset objsale = new sale ‘lookup the correct saleobjsale.id = stridofthissale ‘output the dataresponse.write "this sale was made by " & objsale.salespersonname & _ " to " & objsale.customername ‘tidy up the objectsobjsale.closeset objsale = nothing如果你使用“sale”對象做比打印更多的事,可以讓你省去很多的打字時(shí)間。
計(jì)算中,對象包括“屬性”和“方法”。屬性主要是儲存在對象中的一個(gè)變量,其用法與變量相同。唯一的區(qū)別在于參數(shù)賦值為:strmyvar = "this is a string variant", 而對象屬性為 objobject.property="this is a string variant"。這點(diǎn)非常簡單而有用處。方法可以理解為植入對象中的函數(shù)與過程,可以使用strmyvar = objobject.methodname(strmyvar)來代替strmyvar =functionname(strmyvar)。寫法不同,但功能相同。屬性的一個(gè)例子是對象response中的expireabsolute,response.expiresabsolute = cdate("1 september 1999")。方法的一個(gè)例子是對象response中的write方法,response.write "hello world!"。
vbscript的一個(gè)新特性就是其可以創(chuàng)建新的對象而不需要求諸于花銷時(shí)間都極大的編譯器。我將向讀者展示如何創(chuàng)建對象的類,并希望提供一個(gè)良好的開端。