Implied Global Variables
Consider the script found here: http://jsfiddle.net/DougWare/yeDsf/ which illustrates the issue.
In this sample I have a script block that uses the variable I which is treated as a number. Elsewhere I also use a variable named I to which a string is assigned. Clicking the button yields:
Generally speaking JSLint will catch this problem and warn you that you have created an implied global variable.
Consider the following C# code:
This code results in a compile time error because C# has block scope and the code tries to use I outside of the block in which it is declared (the for block).
Even though i was declared in the for block, it exists and is accessible even after the for block completes.
Within the function inner() the variable input is visible because it is defined by its ancestor function top(). However innerVar is not visible from top() nor is top()’s named argument input visible outside the function top(). In both cases the test for undefined returns true because those variables are undefined at that scope.
Global variables are an Illusion
The fact that functions can see up implies that there must be an outer container that holds everything. This container’s name is window and it is not a function but an object. The window object provides the runtime context and contains properties that let you access things like the document and location as well as methods like alert and events like onload. Therefore, creating an implied global variable by forgetting var is the same operation as adding a member to window.
Global variables are just like local variables but they are local to window and thus visible everywhere to all of the functions contained by the window.
The Most Common Scope Related Error
Thus far you’ve seen two ways to create members on the window object, accidently by forgetting var and deliberately by using window. There is another far more common way that developers can create global variables and unintended name collisions.
Consider a page like this:
Where script.js is as follows:
Both the page and the script use variables named x and y and both use the var keyword. The browser reads and executes script.js first because it is at the top of the page. The script block at the bottom of the page executes last. When it executes the function foo() the output is not 4 but is abcd. This is because whenever you declare a variable that is not contained by a function it is attached to window!
Author: Doug Ware
Author: Doug Ware