HTML and CSS Reference
In-Depth Information
Global variables
Variables declared in the global scope—that is outside any function body—are always global regard-
less of whether or not var is used. Consider the following snippet to experience the subtle differences
between local and global, represented by the var keyword:
var rootServer = ""; // global variable
section = "mobile"; // global variable
function doSomething() {
var temp = 1; // local variable
mode = 0; // global variable, but undefined
until called
The JavaScript runtime environment stores global variables as properties of a hidden object
referenced through the this keyword. Note that browsers often mirror the global object via the
window object.
protecting the global namespace
In nearly any programming language, coding is (much) easier if you can use global variables. Global
variables, however, have downsides too. A critical downside is the risk of name collisions between
variables defined in different parts of your code, third-party libraries, advertising partners, and
analytics libraries. A name collision combined with the dynamic typing of JavaScript variables may
wind up inadvertently modifying the state of the application—with potentially unpleasant anomalies
at run time.
Consider how easy it is to unwittingly create global variables: miss a var and you get a global;
mistype a variable name in an assignment and you get a fresh new global. This latter feature is
possible because JavaScript allows you to use a variable without declaring it first.
There is a workaround. When you need to use global variables, a good technique is to create them
as properties of a wrapper object. You place code similar to the following in a JavaScript file that you
then link from every page:
var Globals = (function() { return this; }());
Next, you make a point of referencing whatever global object you use via the Globals.Xxx
expression, where Xxx is the name of the global variable you want to use. In this way, at least all of
your global variables will stand out in code.
Note JSLint ( )—an online tool for static analysis of JavaScript code—
does help in catching anti-patterns in your code, including the lack of var keywords.
Search WWH ::

Custom Search