|
Test Examples.. Predict the output. Run the code. If you are not correct, trace the code again. Get Help if needed.
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dt d">
<!-- Fig. 10.7: scoping.html --> <!-- Local and Global Variables -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>A Scoping Example</title>
<script type = "text/javascript"> <!-- var x = 1; // global variable
function start() { var x = 5; // variable local to function start
document.writeln( "local x in start is " + x );
functionA(); // functionA has local x functionB(); // functionB uses global variable x functionA(); // functionA reinitializes local x functionB(); // global variable x retains its value
document.writeln( "<p>local x in start is " + x + "</p>" ); }
function functionA() { var x = 25; // initialized each time // functionA is called
document.writeln( "<p>local x in functionA is " + x + " after entering functionA" ); ++x; document.writeln( "<br />local x in functionA is " + x + " before exiting functionA" + "</p>" ); }
function functionB() { document.writeln( "<p>global variable x is " + x + " on entering functionB" ); x *= 10; document.writeln( "<br />global variable x is " + x + " on exiting functionB" + "</p>" ); } // --> </script>
</head> <body onload = "start()"></body> </html>
Scoping #2 Test Prep
<?xml version = "1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dt d">
<!-- Fig. 10.7: scoping.html --> <!-- Local and Global Variables -->
<html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>A Scoping Example</title>
<script type = "text/javascript"> <!-- var x = 1; var y = 4; var z = 5; function start() { var x = 9; document.writeln( "values are " + x + y + z);
functionA(); document.writeln( "<p>values are " + x + y + z + "<p>");
functionB(); document.writeln( "<p>values are " + x + y + z + "<p>");
}
function functionA() { var z = 6; document.writeln( "<p>Avalues are " + x + y + z + "<p>"); x++; functionB(); document.writeln( "<p>Avalues are " + x + y + z + "<p>");
}
function functionB() { var y = 3; document.writeln( "<p>Bvalues are "+ x + y + z + "<p>"); x=x+2; z++; document.writeln( "<p>Bvalues are " + x + y + z + "<p>"); } // --> </script>
</head> <body onload = "start()"></body> </html>
|