ASP 程序

Sub 与 Function 的差别、参数传递、ByVal / ByRef、递归。

Beginner
Key PointsSub 做事不返回值,Function 返回一个值;参数默认 ByRef(传引用),要传值必须写 ByVal。

Sub

ASP
<%
    Sub Greet(name)
        Response.Write "Hello, " & name & "<br>"
    End Sub

    Call Greet("Ada")
    Greet "Bob"                 ' 不用 Call 时不能加括号
%>
Output
Hello, Ada
Hello, Bob

With Call the arguments need parentheses; without it they must not have any. Greet("Bob") is parsed as one expression and only works by luck with a single argument — the most confusing bit of VBScript syntax.

Function

ASP
<%
    Function Add(a, b)
        Add = a + b            ' 给函数名赋值就是返回值
    End Function

    Function IsEven(n)
        If n Mod 2 = 0 Then
            IsEven = True
        Else
            IsEven = False
        End If
    End Function

    Response.Write Add(3, 4) & "<br>"
    Response.Write IsEven(10) & "<br>"
    Response.Write IsEven(7) & "<br>"
%>
Output
7
True
False

A Function returns by assigning to its own name; there is no return. Forgetting the assignment yields an empty value with no error, so assign on every branch.

ByVal 与 ByRef

ASP
<%
    Sub ChangeByRef(x)
        x = x + 1
    End Sub

    Sub ChangeByVal(ByVal x)
        x = x + 1
    End Sub

    Dim a, b
    a = 10 : b = 10
    ChangeByRef a
    ChangeByVal b
    Response.Write a & " / " & b
%>
Output
11 / 10

VBScript parameters are ByRef by default, so changes affect the caller's variable — the opposite of Java and C#. Write ByVal unless you intend to write back.

递归

ASP
<%
    Function Fact(n)
        If n <= 1 Then
            Fact = 1
        Else
            Fact = n * Fact(n - 1)
        End If
    End Function

    Response.Write Fact(5)
%>
Output
120

作用域与 Global

ASP
<%
    Dim pageLevel
    pageLevel = "页面级"

    Sub ShowIt()
        ' 过程内能读页面级变量
        Response.Write pageLevel & "<br>"
    End Sub

    Sub LocalDemo()
        Dim pageLevel            ' 同名局部变量,遮蔽页面级
        pageLevel = "过程级"
        Response.Write pageLevel & "<br>"
    End Sub

    ShowIt
    LocalDemo
    Response.Write pageLevel & "<br>"
%>
Output
页面级
过程级
页面级
Dim-ing a local with the same name as a page-level variable shadows it silently. Option Explicit does not catch this; only naming discipline (e.g. a g_ prefix) does.

Friends & Partners