- The Fundamentals of VBScript
- VBScript Versus VB
- Creating Variables in VBScript
- Concatenating Strings
- Arrays and Loops
- Resizing Arrays
- Inequality Operators
- Conditional Statements
- Select Case Statements
- Working with Arguments
- Beware of Types
- Event Procedure Naming Syntax
- Server-Side Events
- Local Variables
- Script-Level Variables
Working with Arguments
When you consider the code in Listing 3.11, you'll see there is a problem. For the function GetBiggerNumber to work in any other Web page, HTML text elements named text1 and text2 must be on the new page. Otherwise, the code will not work. This is very poor function design.
A function that is designed well maintains internal integrity even if the code is cut and pasted from one Web page to the next. We can remove the text elements' dependency on GetBiggerNumber by using arguments in the function.
An argument is a placeholder for data that you pass into a function. Using arguments makes your functions more independent and reusable. We are going to enhance the GetBiggerNumber function to take two arguments, ArgOne and ArgTwo. Then, when the function is used, we pass the numbers we want to be compared as values for ArgOne and ArgTwo.
Listing 3.12 shows the code for the enhanced version of GetBiggerNumber.
Listing 3.12: Enhancing Functions with Arguments (03asp12.htm)
<HTML> <HEAD> <TITLE></TITLE> </HEAD> <SCRIPT LANGUAGE=VBScript> Function GetBiggerNumber(ArgOne, ArgTwo) Dim x Dim y 'Get the value from the first argument x = CInt(ArgOne) 'Get the value from the second argument y = CInt(ArgTwo) '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() 'Call GetBiggerNumber and pass the 'values in text elements, text1 and text2 'as arguments to the function. text3.value = GetBiggerNumber(text1.value, text2.value) 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>
Again, the output of this code will not look any different from what you see in Figure 3.8. The important thing here is to recognize that all the enhancements have taken place with regard to how the internals of the function work, not to the output behavior).