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.

fiddle(x);<br />

document.write("After function call x ="+x+"");<br />

At the beginning of fiddle, arg1 has a reference to the value of x:<br />

It does not, however, have a reference to x itself. Assigning "New value" to arg1 replaces its<br />

reference to x‘s data with a reference to a new string:<br />

Since the assignment of "New value" isn‘t a modification of x‘s value, it is not reflected in x:<br />

If this discussion went over your head, don‘t worry; it‘s rather advanced material. Just keep the<br />

following rule in mind: functions passed reference types can modify but not replace values in<br />

the calling context.<br />

Global and Local Variables<br />

For most <strong>JavaScript</strong> developers, there are only two basic scopes: global and local. A global<br />

variable is one that is known (―visible‖) throughout a document, while a local variable is one<br />

limited to the particular block of code it is defined within. <strong>The</strong> body of a function has its own<br />

local scope. For example, in the script here, the variable x is defined globally and is available<br />

within the function myFunction, which both prints and sets its value.<br />

// Define x globally<br />

var x = 5;<br />

function myFunction()<br />

{<br />

document.write("Entering function");<br />

document.write("x="+x+"");<br />

document.write("Changing x");

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

Saved successfully!

Ooh no, something went wrong!