應miles的要求,同時也作為類設計的一個例子,我把我設計日期類的過程整理出來,寫成這篇文章,供大家做個參考。也希望這篇文章能拋磚引玉,讓大家寫出更好,更多的類來。文中有不盡的地方,還請指正。 (一)VBscript自定義類 簡單的說,類就是對象,它具有屬性和方法。在vbscript里自定義類比C++,JAVA要簡單得多。下面將設計一個日期類,用來顯示出組合的表單對象。在設計的同時,我們也會說明如何設計自定義類。 1、定義類的語法:class....end class class及end class用來標識類塊的開始和結束,class 標識符后面跟著的是類名稱。現在我們把要設計的日期類命名為:dateclass 語法如下: class dateclass ... end class
在vbscript中使用些類建立新對象時,可以用new運算符。例如: set newdate=new dateclass
2、屬性和方法:private、public和property private 用來定義僅能在類內部訪問的變量和函數;public則用來定義類的界面,也就是可供外部訪問的屬性和方法,沒有成為 private和public的成員,一律視為public;有和時候,我們要讓外部可以訪問,但是要指定訪問的方法,這時候,就要用property,property語法如下: public property [let|set|get] aa(...) ... end property
property 必須和 let、set或get 配合使用。說明如下: let 設置值,如:user.age=100 set 設置對象,如:set user.myobject=nobject get 取得值,如:myage=user.age
3、設計日期類的屬性和方法 現在我們來設計日期類的屬性。為了顯示日期,定義一個classdate,來存放日期,它的類型是public,這樣可以讓用戶在類外部改變它;再設計一個函數來顯示日期,取名為:datedisplay,類型為public,沒有參數。程序如下: <% class dateclass
public classdate
public function datedisplay()
end function
end class %>
4、加入顯示日期的代碼 現在我們來加入datedisplay的代碼,程序如下: <% class dateclass
public classdate
public function datedisplay() '如果沒有指定日期,那么設為當前日期 if classdate="" then classdate=now() end if yy=year(classdate) mm=month(classdate) dd=day(classdate) response.write "<input type=text name=yy size=4 maxlength=4 value="&yy&">年"&vbcrlf response.write "<select name=mm>"&vbcrlf for i=1 to 12 if i=mm then response.write "<option value="&i&" selected>"&i&"</option>"&vbcrlf else response.write "<option value="&i&">"&i&"</option>"&vbcrlf end if next response.write "</select>月"&vbcrlf response.write "<select name=dd>"&vbcrlf for i=1 to 31 if i=dd then response.write "<option value="&i&" selected>"&i&"</option>"&vbcrlf else response.write "<option value="&i&">"&i&"</option>"&vbcrlf end if next response.write "</select>日"&vbcrlf end function
end class %>
把上面的代碼存為dateclass1.asp 好了,現在我們已經寫好了這個日期類,下面來看看使用的情況 5、調用類 include 在其它程序中使用這個類,只要用include 把dateclass1.asp包含進來。下面我們寫一個測試的程序,文件名為 test1.asp <!--#include file="dateclass1.asp" --> <% set newdate= new dateclass response.write "調用顯示:<br>" newdate.datedisplay response.write "<br>顯示classdate的值:<br>" response.write newdate.classdate response.write "<br>設置classdate的值:<br>" newdate.classdate=cdate("2005/6/15") '上一句也可以寫成: 'newdate.classdate="2005/6/15" response.write "<br>再調用顯示:<br>" newdate.datedisplay set newdate=nothing %>
把兩個文件放在同一個目錄下,運行test1.asp 好了,應該已經看到結果了。但是這樣的設計還有一些問題: 1、如果用戶指定的classdate不是日期型,那么日期就會變成1900年1月1日; 2、如果顯示多個日期,表單對象的名字不能是一樣的; 3、最好加入CSS; 4、最好還能加入閏年的判斷; 5、不是每個月都有31天; 帶著這些問題,我們將會繼續........
|