edit-article
Home
Up
Delete
Article Name:
Article Description:
by Don Sagrott - Understanding 'global' - the global object and variables with global scope
Chapter ID/Name:
Status:
Write
Writing
Written
Add Photo:
Owner ID:
Content:
use HTML
Edit Content
<h1 style="text-align: center;">global</h1> <h2>[WHAT]</h2> <ol> <li>] the term 'global' can refer to different things in javascript </li> <ol> <li>] the <em><strong>global object</strong></em> - a native javascript object that 'contains' all the variables that have global scope, as well as its own properties and methods. This object exists for all javascript pages.</li> <li>] OR</li> <li>] <em><strong>a 'variable that has global scope'</strong></em> - meaning that the variable can be accessed from anywhere within your web page/site</li> </ol></ol> <h2>[WHY]</h2> <ol> <li>] <em>the global object</em></li> <ol> <li><em>] </em></li> </ol> <li>] global variables</li> <ol> <li>] typically you want to avoid using global variables</li> </ol></ol> <h2>[WHY NOT]</h2> <ol> <li><strong>] global variables</strong></li> <ol> <li>] any javascript code can access, read or write, the value of any global variables</li> <li>] namespace pollution - the more you use global variables, the more likely that a naming conflict, which will result in NO errors but some unpredictable </li> </ol></ol> <h2>[WHERE]</h2> <ol> <li><strong>] <a href="/view/article?id=2706" target="_blank">global object</a> </strong></li> <ol> <li>] a complete listing of the properties and methods of the Global object</li> </ol></ol> <h2>[WHEN]</h2> <ol> <li>] global object</li> <ol> <li>] everywhere - exists for each javascript, created automatically</li> </ol> <li>] global variables</li> <ol> <li>] avoid</li> </ol></ol> <h2>[EXAMPLE]</h2> <ol> <li>]</li> </ol> <h2>[HOW-TO]</h2> <ol> <li>] use the var keyword to specify that your variable will be local to the function that is declared in.</li> <li>] var x = "name"; // var will be "local" to the function where it is declared</li> <li>] x = "name"; // var will have global scope</li> <li>] var x= "name"; // declared outside of any function would also have global scope </li> </ol> <h2>[REFERENCE]</h2> <ol> <li>] <a href="https://gist.github.com/hallettj/64478">https://gist.github.com/hallettj/64478</a> - a tutorial demonstrating why global variables are bad</li> </ol><hr /><ol> <li>] ?? - helloWorld scope / global object</li> <li>] EX js-101-a </li> </ol>