Online Documentation Server
 ПОИСК
ods.com.ua Web
 КАТЕГОРИИ
Home
Programming
Net technology
Unixes
Security
RFC, HOWTO
Web technology
Data bases
Other docs

 


 ПОДПИСКА

 О КОПИРАЙТАХ
Вся предоставленная на этом сервере информация собрана нами из разных источников. Если Вам кажется, что публикация каких-то документов нарушает чьи-либо авторские права, сообщите нам об этом.




Previous Table of Contents Next

Caution:  Netscape Navigator allows you to use arguments rather than functionName.arguments. However, Microsoft’s Internet Explorer 3.0 generates an error when you implement that shortcut. If you want to be on the safe side, you can use the following statement at the beginning of the function:

var args = functionName.arguments

You can then use args in the regular way (args[0],args.length, etc.).

The ability to refer to the arguments passed to the function during the last call of the function often trips up JavaScript scripters. For example, consider the following script:

function func() {
   document.write(func.arguments[0] + "<BR>")
}

func("a")
func("b")
func()
func("c")

The output of this script is:

a
b
b (!)
c

The only surprising line is the third one. The argument printed is the one passed to the function during the previous call. The first argument of the current call cannot be printed because there is no such argument. At times, you will receive unexpected results from the func.arguments.length property, as well as from the elements of the array itself. See Chapter 13, Arrays, for a possible remedy.

Note, also, that you may only refer to the arguments array from within the function.



Figure 9-6.  An alert dialog box&151;each line is a distinct argument handed to the function

The scope of the arguments object’s properties is the current function, so it can only be used inside a function. You can use loop statements to print a list of arguments handed to a function:

function createList() {
 var result = ""
 for (var i = 0; i < createList.arguments.length; ++i) {
  result += createList.arguments[i] + "\r"
 }
 alert(result)
}

Here is a simple function call:

createList("S", "H", "I", "R", "A", "N")

When invoked with the preceding statement, the function generates the following dialog box:


Figure 9-7.  A uniquely designed alert box.

Here is a useful function that creates special alert boxes:

<HTML>
<HEAD>
<TITLE>Using the arguments object</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- hide content from old browsers

function specialAlert(verticalLine) {

// creates an alert box with a short message
// on the left-hand side.

var verLength = verticalLine.length // length of string
var horLines = specialAlert.arguments.length - 1
// total horizontal lines
var maxLength = (verLength + 1 >= horLines) ? verLength+1:horLines
// assigns the greater value to maxLength
var text = "\r\r"
text += "*******************\r"

 for (i = 0; i < maxLength; i++) {
  if (i < verLength)
   text += "**\t" + verticalLine.charAt(i) + "\t**\t"
  else
   if (i == verLength)
text += "******************"
   else
text += "\t"
   if (i < horLines)
text += specialAlert.arguments[i + 1] // exclude first argument
   text += "\r"
  }

 alert(text)
}
specialAlert("Tomer",
  "Tomer Shiran co-authored this JavaScript book.",
  "He worked hard writing the examples.")

// end hiding content from old browsers -->
</SCRIPT>
</HEAD>
<BODY>
</BODY>
</HTML>

Example 9-1 (ex9-1.htm). A simple function that creates uniquely formatted alert boxes.

Here is the output of Example 9-1:

First of all, you should be aware that the first argument handed to the function is the string that is displayed vertically, whereas each additional argument represents a single horizontal line in the final layout.

The first portion of the function assigns the number of characters in the vertical line to the variable verLength. The length property is discussed later in the book. The number of horizontal lines is then assigned to horLines. This value is equal to the number of arguments minus 1, because the first argument (vertical line’s string) is excluded. The greater of these two values (verLength and horLines) is assigned to max. The variable text, that holds the entire string displayed in the alert box, is initialized with two carriage return characters. After a line of asterisks followed by a carriage return is assigned to the variable text, the loop begins. The loop is executed max times. During each iteration, the following statements are executed:

  • If the vertical string is not finished, the next character is printed, with a tab character and two asterisks on both sides. If the vertical string has finished during the previous execution of the loop, the expression
    i == verLength
    evaluates to true, and the bottom row of asterisks is assigned to the variable text.
  • If additional horizontal lines remain, they are printed following the current row of the rectangle.

After the loop terminates, all that is left is to display the final string in an alert box.

Notice the use of the expression

verLength + 1

inside the function. We use it because the loop should execute at least one time more than the number of characters in the vertical string, because the bottom panel of the rectangle is printed during that execution. It is not possible to assign that row of asterisks after the loop, because it will not work properly when the number of horizontal lines exceeds the length of the vertical string. Also notice that we use the charAt() method to refer to a specific character in a string. The first character of the string is returned by the method charAt(0), the second character is returned by charAt(1), and so forth. The length property returns the number of characters in the string. String objects, their methods, and properties are discussed in Chapter 16, Handling Strings.

Creating Functions with Default Arguments

JavaScript does not support functions with default arguments. In C++, these are the values supplied to the parameters in a function’s prototype. Calling the following function at the beginning of a function is a simple workaround you can use in JavaScript:

function checkDefault(parameter, defaultValue) {
  if (typeof parameter == "undefined")
 return defaultValue
  /* else */
 return parameter
}

The appropriate call to this function is:

parameterName = checkDefault(parameterName, defaultValue)

Previous Table of Contents Next


With any suggestions or questions please feel free to contact us