將重複邏輯封裝為 Function(有回傳值)與 Sub(無回傳值)是構建可維護 ASP 應用的基石。本文深入解析宣告語法、參數傳遞機制、呼叫慣例、變數作用域與重構模式。
<%
' 宣告
Sub SubName(param1, param2, ...)
' 陳述式
End Sub
' 呼叫兩種方式
Call SubName(arg1, arg2) ' 有 Call 關鍵字,參數需括號
SubName arg1, arg2 ' 無 Call,參數不加括號
' 實戰範例:記錄系統日誌
Sub LogEvent(eventType, message, userId)
Dim conn, sql
Set conn = GetConnection()
sql = "INSERT INTO SysLog (EventType, Message, UserID, LogTime) VALUES (?, ?, ?, Now())"
ExecuteNonQuery sql, Array(eventType, message, userId)
' 這裡假設 ExecuteNonQuery 為前文定義的封裝函數
End Sub
' 使用
Call LogEvent("LOGIN", "用戶登入", Session("UserID"))
LogEvent "LOGOUT", "用戶登出", Session("UserID")
%>
<%
' 宣告:函數名賦值即為回傳值
Function FunctionName(param1, param2, ...)
' 計算邏輯
FunctionName = resultValue ' 關鍵:將結果賦值給函數名
End Function
' 實戰範例:計算圓面積
Function CircleArea(radius)
If radius < 0 Then
CircleArea = -1 ' 錯誤代碼
Exit Function
End If
CircleArea = 3.14159265359 * radius * radius
End Function
' 使用
Dim area : area = CircleArea(5)
Response.Write "面積:" & area ' 78.5398...
' 進階:多重返回點
Function SafeDivide(dividend, divisor)
If divisor = 0 Then
SafeDivide = Null ' 或 Err.Raise
Exit Function
End If
SafeDivide = dividend / divisor
End Function
%>
| 關鍵字 | 行為 | 預設 | 適用場景 |
|---|---|---|---|
ByRef | 傳址:程序內修改影響外部變數 | 是 | 需修改引數、大型物件避免複製 |
ByVal | 傳值:複製數值,程序內修改不影響外部 | 否 | 輸入參數、基本型別、防止副作用 |
<%
Sub ModifyByRef(ByRef num)
num = num * 2
End Sub
Function ModifyByVal(ByVal num)
num = num * 2
ModifyByVal = num
End Function
Dim x : x = 10
ModifyByRef x
Response.Write "ByRef 後 x = " & x & "
" ' 20
Dim y : y = 10
Dim z : z = ModifyByVal(y)
Response.Write "ByVal 後 y = " & y & ", 回傳 z = " & z & "
" ' y=10, z=20
%>
<%
' VBScript 無 ParamArray,使用陣列或 Dictionary 模擬
Function SumValues(values)
Dim total, i
total = 0
If IsArray(values) Then
For i = 0 To UBound(values)
If IsNumeric(values(i)) Then total = total + values(i)
Next
End If
SumValues = total
End Function
Response.Write SumValues(Array(1, 2, 3, 4, 5)) ' 15
Response.Write SumValues(Array(10, 20)) ' 30
%>
<%
' 階乘遞迴
Function Factorial(n)
If n <= 1 Then
Factorial = 1
Else
Factorial = n * Factorial(n - 1)
End If
End Function
' 樹狀結構遞迴:產生分類路徑
Function GetCategoryPath(catId, separator)
Dim sql, rs, parentId, parentPath
sql = "SELECT ParentID FROM Categories WHERE CategoryID = ?"
Set rs = ExecuteQuery(sql, Array(catId))
If rs.EOF Or rs("ParentID") = 0 Then
GetCategoryPath = GetCategoryName(catId)
Else
parentId = rs("ParentID")
rs.Close
parentPath = GetCategoryPath(parentId, separator)
GetCategoryPath = parentPath & separator & GetCategoryName(catId)
End If
If IsObject(rs) Then rs.Close : Set rs = Nothing
End Function
%>
Dim/Public/Private 在 <% %> 外部或腳本開頭宣告,全腳本可見Option Explicit)<%
Option Explicit ' 強制變數宣告,放在最頂端
Dim moduleVar ' 模組層級
Sub DemoScope()
Dim localVar ' 程序層級
localVar = "區域"
moduleVar = "模組層級被修改"
End Sub
DemoScope()
Response.Write moduleVar ' 輸出:模組層級被修改
' Response.Write localVar ' 錯誤:未宣告
%>
<%
' ===== utils.asp 共用函數庫 =====
Function HTMLEncodeSafe(str)
If IsNull(str) Then HTMLEncodeSafe = "" : Exit Function
HTMLEncodeSafe = Server.HTMLEncode(str)
End Function
Function FormatCurrency(amount)
FormatCurrency = FormatNumber(amount, 2, True, False, True)
End Function
Function IsValidEmail(email)
Dim regex : Set regex = New RegExp
regex.Pattern = "^[\w\.-]+@[\w\.-]+\.\w{2,}$"
regex.IgnoreCase = True
IsValidEmail = regex.Test(email)
End Function
' ===== 業務邏輯層 =====
Function CreateUser(username, email, password)
If Not IsValidEmail(email) Then
CreateUser = "Email 格式錯誤"
Exit Function
End If
' ... 資料庫操作
CreateUser = "success"
End Function
' ===== 頁面使用 =====
' <!--#include file="utils.asp"-->
Dim result : result = CreateUser("john", "john@example.com", "pwd123")
%>
GetUser、CalculateTax、ValidateInputIf IsMissing(param) Then param = default(VBScript 無 IsMissing,用 If IsEmpty(param) Or param = "" Then)Err.Raise 配合 On Error Resume Next