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

Testing Evaluation

A hidden feature of Netscape Navigator (but not of MSIE 3.0x) enables you to experiment with evaluation in the browser’s window. You can reach this window by simply entering javascript: in the Location box. Another way to do this is by choosing Open Location from the File menu. Then type javascript: to open the evaluation window.

The evaluation window contains two frames. The field at the bottom frame is used to accept your input and the upper frame displays the Navigator’s computation results. To experiment with this tool, enter the following statements at the javascript typein field at the bottom:

var firstNumber = 120
var secondNumber = firstNumber – 60
firstNumber
secondNumber
var finalAverage = (firstNumber + secondNumber) / 2
finalAverage
secondNumber = firstNumber
finalAverage
finalAverage > secondNumber

Before you enter these expressions, try to figure out what they evaluate to. Then type them in the field at the bottom frame, with a carriage return (Enter) after each statement.

After you enter all of the preceding statements, the browser’s window should look like the following:


Tip:  You can also use the mocha: URL instead of javascript:, as shown in Figure 5-4.


Functions

Function Definition

You have already seen that a function is actually a multiline statement which includes many nested statements. Just like variables, you must define a function before you can call it.

You may recall from the previous chapter that functions are defined using the keyword function, followed by the name of the function. The same rules that apply to variable names apply to functions. Since a function usually does something besides storing a value, it is common to include a verb in its name. The function’s parameters are written in brackets after the name. A command block follows the parameters. The syntax of a function definition is:

function functionName([parameters]) {
  [statements]
}

Parameters are local variables that are assigned values when the function is called. At this point, you should always give a name to every parameter.

In a formal syntax specification, the square brackets “[” and “]” usually denote optional elements. Since a function does not have to have parameters or statements, they are both enclosed in such brackets. The curly braces enclosing the function body can be placed anywhere, following the parameters’ section. The following functions are valid:

function functionName([parameters]) {[statement1]; [statement2]; ...}

function functionName([parameters])
{
  [statement1]
  [statement2]
  .
  .
  .
}

The following example demonstrates a function declaration:

<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
<!-- hide script contents from old browsers

function square(number) {
  document.write("The call passed ",
   number, // the function's parameter
   " to the function.<BR>",
   number, // the function's parameter
   " square is ",
   number * number,
   ".<BR>")
}

// *** add function call

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

Example 5-2 (ex5-2.htm). A function definition (deferred code).


Figure 5-5.  HTML content generated by two JavaScript functions.

Example 5-2 does not print anything to the browser’s window, nor does it generate any other form of output. The reason is that the function is only defined in the script but is never called. When the browser locates a function, it loads its statements into the memory, ready to be executed later.

Calling Functions

In order to execute the set of statements located in the function block, you must call the function. The syntax of a function call is:

functionName([arguments])

By adding the statement square(5) to Example 5-2, at the specified place, we call the function. The statements in the function are executed, and the following message is output:

The call passed 5 to the function.
5 square is 25.

You can also call a function from within another function, as the following example demonstrates:

<HTML>
<HEAD>
<TITLE>Calling a function from within another function</TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!-- hide script contents from old browsers

function makeBar() {
  var output = "<HR ALIGN='left' WIDTH=400>"
  document.write(output)
}

function makeHeader(text, color, size) {
  var output = "<FONT COLOR='" + color + "' SIZE=" +
  size + ">" + text + "</FONT>"
  document.write(output)
  makeBar()
}

makeHeader("JavaScript Examples", "red", "+4")

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

Example 5-3 (ex5-3.htm). A function call in a function block.

Example 5-3 summarizes many of the terms discussed in this chapter. It includes two function definitions. In both functions, the output is assigned to a variable (output) and then printed to the client window using the document.write() method. Assigning strings to variables before printing them is extremely useful when the string is long (you want to print a lot of data). You can see the result of Example 5-3 in Figure 5-5.

Summary

Variables are the cornerstone of most programming languages. In order to write a script you need to use variables. You’ve learned how to create variables in JavaScript and how to name them. Functions are another important element in JavaScript. You can use functions to split code into smaller segments. From now on, we will use functions in all of our scripts. Some functions will be general functions that you can add to your personal “library of functions.” You can call them from there whenever you need them in your scripts. We will use functions even in short and simple scripts, just to provide you with more experience. This chapter also taught you how to use the hidden javascript: and mocha: evaluation tools. We also talked about various expression evaluation techniques. You probably still feel that our example scripts are useless, but be patient and you will be amazed to find out what JavaScript can do, and how complex these scripts can get.

Previous Table of Contents Next


With any suggestions or questions please feel free to contact us