Home > Articles

  • Print
  • + Share This

Function

A Function is a procedure that returns a value upon execution. You construct it very much in the same way that you do a Sub. However, instead of using the Sub <keyword> you use the Function <keyword>. Moreover and most importantly, you pass a value out of a Function by assigning the value to the function's name. Writing well-designed functions is the first step toward creating well-encapsulated code. Listing 3.11 shows you code in which the Sub GetBiggerNumber has been transformed to a Function called GetBiggerNumber(). The function returns a value, which depends on the larger value entered into text elements on a Web page.

Listing 3.11: Returning a Value from a Function (03asp11.htm)

<HTML>
<HEAD>
<TITLE></TITLE>
</HEAD>
<SCRIPT LANGUAGE=VBScript>


  Function GetBiggerNumber()
    Dim x
    Dim y
    'Get the First Number
    x = CInt(text1.value)
    'Get the Second Number
    y = CInt(text2.value)

    'Pass the larger number out of the
    'function by assigning the value to
    'the function's name.
    If x > y Then
      GetBiggerNumber = x
    Else
      GetBiggerNumber = y
    End If

  End Function

  Sub button1_OnClick()
    'Use the return of the function, GetBiggerNumber
    'as the value to assign to the text element,
    'text3.
    text3.value = GetBiggerNumber()
  End Sub
</SCRIPT>

<BODY>

<P>First Number: <INPUT name=text1 size=15></P>

<P>Second Number:
<INPUT name=text2 size=15></P>

<INPUT type="button" value="Get Bigger Number" name=button1>

<P>Bigger Number: <INPUT name=text3 size=15></P>

</BODY>
</HTML>

Listing 3.11 changes the internals of the page. However, the output of that listing is much the same as what is shown in Figure 3.8.

  • + Share This
  • 🔖 Save To Your Account

Related Resources

There are currently no related titles. Please check back later.