17.11.2015 Views

JavaScript_Succinctly

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

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

object.<br />

}<br />

// Logs bar, foo's value is found via the scope chain in the head<br />

console.log(foo);<br />

} ();<br />

myApp();<br />

<br />

Had I placed the foo property outside of the global scope, the console.log function<br />

would return undefined. This is demonstrated in the next code example.<br />

Sample: sample66.html<br />

<br />

var myFunction = function () { var foo = 'bar' }; // foo is now in the<br />

scope of myFunction()<br />

var myApp = function () {<br />

var run = function () {<br />

console.log(foo); // foo is undefined, no longer in the global<br />

scope, an error occurs.<br />

} ();<br />

}<br />

myApp();<br />

<br />

In the browser environment, this is why global property methods (e.g.,<br />

window.alert()) can be invoked from any scope. What you need to take away from<br />

this is that anything in the global scope is available to any scope, and thus gets the title<br />

of "global variable" or "global property.”<br />

Notes<br />

There is a slight difference between using var and not using var in the global scope<br />

(global properties vs. global variables). Have a look at this Stack Overflow exchange for<br />

the details: Difference between using var and not using var in <strong>JavaScript</strong>.<br />

Referring to the head object<br />

There are typically two ways to reference the head object. The first way is to simply<br />

reference the name given to the head object (e.g., in a web browser this would be<br />

80

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

Saved successfully!

Ooh no, something went wrong!