HTML and CSS Reference
In-Depth Information
EXAMPLE
7.5
<html>
<head><title>Function Scope</title>
<script type="text/javascript">
1
var name="William";
// Global variable
var hometown="Chico";
2
function greetme(){
3
var name="Daniel";
// Local variable
var hometown="Husingen";
4
alert("In function the name is " +
name
+
" and hometown is "+
hometown
);
5
}
</script>
</head>
<body>
<script type="text/javascript">
6
greetme();
// Function call
7
alert("Out of function, name is "+
name
+
8
" and hometown is " +
hometown
);
</script>
</body>
</html>
EXPLANATION
1
The variables called
name
and
hometown
are global in scope. They are visible
throughout the JavaScript program.
2
The function called
greetme()
is declared and defined.
3
Any variables declared within a function with the
var
keyword are local to that
function. In fact, you must use the
var
keyword when declaring local variables;
otherwise, the variables will be global. The variable called
name
has been declared
inside the function. This is a local variable and has nothing to do with the global
variable of the same name on line 1. The function variable will go out of scope;
that is, it will no longer be visible, when the function ends on line 6, at which
point the global variable will come back in scope. If the variable,
name
, had been
given a different name, within the function, such as
name2
or
myName
, then the
global variable would have remained in scope within the function.
4
The variable called
name
and
hometown
were defined inside this function and are
local in scope. They will stick around until the function exits.
5
The closing curly brace marks the end of the function definition.
6
The function
greetme()
is called here.
7
The global variable called
name
has come back into scope.
8
The global variable called
hometown
is still in scope (see Figure 7.8).