Global Code

We've seen that code can be organized into functions, subroutines, and classes, and that some subroutines (and an occasional function) can be executed automatically if they are event handlers and the event they handle fires. However, that seems to offer a relatively limited "hook" for a script to run, and it doesn't seem to make it possible for a script to perform whatever initialization might be required in order for its event handlers to function successfully.

Global codethat is, code outside functions and subroutinesis the answer to this dilemma. It is executed automatically when the script loads or as the HTML on the page is parsed. The precise meaning of global code and the exact way in which it is executed depends on the host environment for which the script is written. We'll examine these in turn.

2.3.1 Active Server Pages

In ASP, global code is synonymous with code in direct ASP commandsit is script that is preceded by the <% or <%= tags and terminated by the %> tag. (For details on how script is embedded within in ASP page, see Chapter 5.) This code is executed automatically as the page's HTML is parsed.

It is also possible to include global code in tags in an ASP. However, this is not genuine global code; aside from variable declarations, the order in which this code is executed is undefined.

Figure 2-1 shows the web page produced by Example 2-7, which illustrates global code in an Active Server Page. Note that although the variable x is defined and assigned a value in global code within the

 

An Active Server Page

The current value of x is <%= x %>

<% Dim y y = 20 If x = 0 Then x = 10 %> Value returned by Increment function: <%= Increment(x) %>

Value returned by Increment function: <%= Increment(x) %>

Value returned by Decrement function: <%= Decrement(x) %>

The value of x is now <%= x %>. The value of y is <%= y %>.

Figure 2-1. The web page produced by Example 2-7

We can draw the following conclusions from Example 2-7:

Категории