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

If you declare global variables inside a function, you must assign an initial value to the variable; otherwise, JavaScript returns an error. The following script segment and screen captures demonstrate this fact:

function foo() {
 // local variable declarations
 var a // without initialization
 var b = 0 // with initialization

 // global variable declarations
 c // without initialization -- error!
 d = 0 // with initialization
}
foo()


Figure 9-4.  An error message appears when you attempt to declare a global variable inside a function without initializing it (Netscape Navigator).


Figure 9-5.  An error message appears when you attempt to declare a global variable inside a function without initializing it (Microsoft Internet Explorer).

Notice that the variable does not hold an undefined value as it would if the declaration used the var keyword—it causes an error instead.

The var keyword is used to “officially” declare variables. JavaScript remembers only the scope of variables that are declared in that fashion. It recognizes other variables during the execution of the script, and automatically refers to them as global variables. Although it does not really matter whether or not you use var to declare global variables in the main script, it might affect the result of the script under certain circumstances. If you do not use var and, when the variable is still undefined, you use it in a value-requiring statement, an error will occur. But this is an easy problem because you get a message about it. The problem with the var declaration is that not all statements that require a variable with a meaningful value use the undefined string when the variable has no value. The basic document.write() statement does not do so on Windows 3.1x, for example. If you try to print the value of an undefined variable with document.write() or document.writeln() using Netscape Navigator for Windows 3.1x, nothing is printed. It then becomes a real challenge to detect and correct a problem caused by an undefined variable. Note, also, that this bug does not exist on all versions of Netscape Navigator. Take a look at the following HTML script definition:

<SCRIPT>
<!--

a = "<HR>"
document.write(a + b + a)
var b

// -->
</SCRIPT>

Under Netscape Navigator for Windows 3.1x this immediate script simply prints two horizontal rules. However, on other platforms, it prints two horizontal rules with the string undefined in between.

What are Functions?


Note:  Throughout this chapter and the previous ones, we did not pay much attention to many important details related to functions. The following section discusses parameters, return values, and other important concepts. You should read this section, even if you feel comfortable with functions. A complete understanding of functions will be necessary later when we discuss objects and methods.


Functions group a sequence of statements to perform a specific task or a function. Functions, as opposed to methods, do not belong to an object that encapsulates them with related data. JavaScript features many built-in functions which are presented later in the book. Such functions are predefined.

Defining Functions and Calling Them

We have spoken much about defining functions. The general syntax of a function definition is

function functionName([parameters]) {
 statements
}

and the form of a function call is

functionName(arguments)

Function Parameters

Sometimes you want to create a function that accepts values when it is invoked. The function should then be able to use these values to perform a specific task. When you define a function, you should specify the names by which you refer to the custom values handed off to the function from outside. These names must follow the same rules that apply to identifiers in the language.

Parameters act like local variables, so they exist only inside the function where they are defined. Therefore, a parameter may use the same name as a global variable or a local variable in a different function. You can manipulate and modify the value of a parameter as if it were a common variable. There is no need to explicitly declare a parameter inside the function’s body as you would with a regular variable.

JavaScript is loosely typed, so you do not specify the data type of the arguments as in C++, Java, Pascal, and other strictly typed programming languages. Both variables and literals can be passed to a function. All parameters in a function definition header should be delimited by the low-precedence comma operator (,). Here is a simple JavaScript function with two parameters:

function printName(name, ruleWidth) {
 document.write("<CENTER><H1>" + name + "</H1></CENTER>")
 document.write("<HR WIDTH=" + ruleWidth + "%>")
}

You can call this function with a simple function call, such as:

printName(prompt("Enter your name:", "John Doe"), 60)


Note:  Arguments are the specific values you assign to parameters. These terms are sometimes considered exchangeable, even by advanced programmers. It is sometimes difficult to distinguish between them, so you might disagree with some of the terms in this chapter.


Using the Argument Array

JavaScript supports functions that accept a variable number of arguments. The first argument is functionName.arguments[0], the second one is functionName.arguments[1], the third one is functionName.arguments[2], and so on. The number of arguments handed to the function is stored in the length property of the arguments object; that is:

functionName.arguments.length. The following script demonstrates this concept:

function calc() {
  document.write("The first argument is ",
  calc.arguments[0], "<BR>")
  document.write("The fourth argument is ",
  calc.arguments[3], "<BR>")
  document.write("There are ", calc.arguments.length,
  " arguments<BR>")
}

var company = "Netscape"
calc(2, 999, "internet", company, 0.0)

The script’s output is:

The first argument is 2
The fourth argument is Netscape
There are 5 arguments

Previous Table of Contents Next


With any suggestions or questions please feel free to contact us