Excerpt: Scope of variables in Javascript
TheScopeOf a variable is all parts of a program where it is visible. Being visible means that the variable has been declared and is available for use. A variable that is visible everywhere in the program hasGlobalScope. a variable that is visible only in a specific context-a function, for example-hasLocalScope.ContextIs the set of defined data that make up the execution environment. when the browser starts, it creates the global context in which JavaScript will execute. this context contains the definitions of the features of the Javascript language (ArrayAndMathObjects, for example) in addition to browser-specific objects likeNavigator.
|
Note |
If you're a javascript beginner, you may wish to only skim the next few sections on scope, and come back to them when you're more comfortable with the language. |
Variable scope and functions
When a function is invoked, the interpreter creates a new local context for the duration of its execution. all variables declared in the function (including its arguments) exist only within this context. when the function returns, the context is destroyed. so, if you wish to preserve a value within SS multiple function cals, you might need to declare a global variable.
|
Note |
Javascript lacks static variables like C-You wowould have to use global variables to achieve this effect. |
When a variable is referenced in a function, the interpreter first checks the local context for a variable of that name. if the variable has not been declared in the local context, the interpreter checks the enclosing context. if it is not found in the enclosing context, the interpreter repeats the process recursively until either the variable is found or the global context is reached.
It is important to note that the contexts are checked with respect to the source code and not the current call tree. This type of scoping is calledStatic scoping(OrLexical scoping). In this way, locally declared variables canHideVariables of the same name that are declared in an enclosing context. The following example extends strates variable hiding:
var scope = "global";function myFunction() { var scope = "local"; document.writeln("The value of scope in myFunction is: " + scope);}myFunction();document.writeln("The value of scope in the global context is: " + scope);
The result is shown inFigure 3-2. The local variableScopeHas hidden the value of the global variable namedScope. Note that omittingVaRFrom the first lineMyfunctionWocould assign the value "local" to the global variableScope.
Figure 3-2: A local variable hides a global variable of the same name.
There are some important subtleties regarding variable scope. the first is that each browser window has its own global context. so it is unclear at first glance how to access and manipulate data in other browser windows. fortunately, JavaScript enables you to do so by providing access to frames and other named windows. the mechanics of cross-window interaction is covered in later chapters, figChapter 12.
The second subtlety related to scoping is that, no matter where a variable is declared in a context, it is visible throughout that context. this implies that a variable declared at the end of a function is visible throughout the whole function. however, any initialization that is already ded in the Declaration is only med when that line of code is reached. the result is that it is possible to access a variable before it is initialized, as in the following example:
function myFunction() { document.writeln("The value of x before initialization in myFunction is: ", x); var x = "Hullo there!"; document.writeln("The value of x after initialization in myFunction is: ", x);} myFunction();
The result is shown inFigure 3-3. Note howScopeHasUndefinedValue before it is initialized.
Figure 3-3: variables may be visible without yet being initialized.
The third Subtlety has to do with static scoping. Consider the following code,
var scope = "global";function outerFunction(){ var scope = "local"; innerFunction();}function innerFunction(){ alert("The value of scope is: " + scope);}outerFunction();
Which results in:
This example extends strates a critical aspect of static Scoping: the valueScopeSeen inInnerfunctionIs the value present in enclosing the global context:"Global ."It does not see the value set inOuterfunction. That valueScopeIs local to that function and not visible outside of it. The correct valueScopeWas found by examination of the enclosing context in the original JavaScript source code. The interpreter can infer the correct value by "static" Examination of the program text. Hence the name "static scoping ."
Variable scope and event handlers
We saw that variables declared inside functions are local to that function. the same rule applies to JavaScript encoded in Event Handlers: the text of the event handler is its own context. the following script extends strates this fact. it declares a global variableXAs well as a variableXWithin an event handler:
<<script type="text/javascript">> var x = "global";<</script>><<form action="#" method="get">><<input type="button" value="Mouse over me first" onmouseover="var x = 'local'; alert('Inside this event hander x is ' + x);" />><<input type="button" value="Mouse over me next! " onmouseover="alert('Inside this event hander x is ' + x);" />><</form>>
Move the mouse over the first button to see that the valueXIn that context has been set to "local". You can see thatXIs not the same as the globalXBy then moving the mouse over the second button. The value printed by the second button is"Global", Indicating thatXSet in the first handler was not the global variable of the same name.
Remember that because Javascript is statically scoped, It's only variables declaredWithin the textOf an event handler that have their own context. Consider this example:
<<script type="text/javascript">>var x = "global";function printx(){ alert("Inside this function x is " + x);}<</script>><<form action="#" method="get">><<input type="button" value="Mouse over me!" onmouseover="var x = 'local'; printx();" />><</form>>
You can see that the valueXThat is printed is"Global". Static scoping at work again: since the context of the FunctionPrintxIs global, it doesn' t see the local value set in the event handler text.
Execution contexts
The preceding discussion of how variable names are resolved hints at the fact that execution contexts vary dynamically and reside within one another. for example, if a variable referenced in the text of an event handler cannot be found within that event handler's context, the interpreter "widens" its view by looking for a global variable of the same name. you can think of the event handler's local context as residingWithinThe global context. If a name can't be resolved locally, the enclosing (global) scope is checked.
In fact, this is exactly the right way to think about execution contexts in JavaScript. an (x) HTML document can be thought of as a series of embedded contexts: An all-enclosing JavaScript global scope within which resides a browser context, within which resides the current window. inside the window resides a document, within which might be a form containing a button. if script executing in the context of the button references a variable not known in the button's context, the interpreter wocould first search the form's context, then the document's, then the window's, the browser's, and eventually the global context.
The exact details of how this works comprise JavaScript'sObject Model, A subject discussed in later chapters. A comprehensive knodge DGE of the topic is not really required to program in Javascript, but helpsTremendouslyIn understanding where the objects available to your scripts come from, and how they are related. It will also go a long way in setting you apart from the typical JavaScript developer!
Recorded from: javascript 2.0-the complete referenceThomas Powell,Fritz Schneider,Second edition,