11.12.2012 Views

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

JavaScript 2.0-The Complete Reference, Second ... - freecodingtutorial

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

<strong>The</strong>re are some important subtleties regarding variable scope. <strong>The</strong> first is that each browser<br />

window has its own global context. So it is unclear at first glance how to access and manipulate<br />

data in other browser windows. Fortunately, <strong>JavaScript</strong> enables you to do so by providing<br />

access to frames and other named windows. <strong>The</strong> mechanics of cross-window interaction is<br />

covered in later chapters, particularly Chapter 12.<br />

<strong>The</strong> second subtlety related to scoping is that, no matter where a variable is declared in a<br />

context, it is visible throughout that context. This implies that a variable declared at the end of a<br />

function is visible throughout the whole function. However, any initialization that is included in<br />

the declaration is only performed when that line of code is reached. <strong>The</strong> result is that it is<br />

possible to access a variable before it is initialized, as in the following example:<br />

function myFunction()<br />

{<br />

document.writeln("<strong>The</strong> value of x before initialization in myFunction<br />

is: ", x);<br />

}<br />

var x = "Hullo there!";<br />

document.writeln("<strong>The</strong> value of x after initialization in myFunction<br />

is: ", x);<br />

myFunction();<br />

<strong>The</strong> result is shown in Figure 3-3. Note how scope has undefined value before it is initialized.<br />

Figure 3-3: Variables may be visible without yet being initialized.<br />

<strong>The</strong> third subtlety has to do with static scoping. Consider the following code,<br />

var scope = "global";<br />

function outerFunction()<br />

{<br />

var scope = "local";<br />

innerFunction();

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!