HTML and CSS Reference
In-Depth Information
name. Note that they don't over
write
them, they over
ride
them—meaning that you can't
access the overridden values. The following code demonstrates this point:
window.onload
…
var scaleX = 0.0;
…
document.getElementById("Div4").onclick = function () {
var scaleX = -3;
alert(scaleX);
}
function scaleDiv() {
//code to scale the Div by a factor of scaleX
}
In this code, if your intention is to use the
scaleX
variable declared globally within the
scaleDiv
function, the results should be unexpected. That's because the function assigned to
the
onclick
event handler also declares a variable named
scaleX
. The value in the
alert
window
within the
onClick
function is -3, not 0.0, and when the
scaleDiv
function accesses the
scaleX
variable, the value is 0.0. Scoping problems such as these highlight why you must always pro-
vide meaningful names to variables. Meaningful names can help prevent accidentally naming
variables the same thing.
The global namespace is where all the native JavaScript libraries live. In Internet Explorer, the
window
object references the global namespace. Everything this object exposes is global.
The global namespace has far more functionality than this topic can cover; however, you've
already seen some examples of the objects in the global namespace used in this chapter,
including the Web Storage API and the Geolocation API. The global namespace includes other
nested namespaces, such as Math, WebSocket, and JSON.
The global namespace is available to
all
code within an application session. With the
increasing number of third-party libraries in use, and as applications become more complex
and require the use of such libraries, the potential for naming conflicts increases. Names of
classes within a namespace must be unique. If multiple developers define a namespace with
the same name, the JavaScript runtime can't identify which namespace they intended to use.
This is why keeping your objects out of the global namespace is important.
One strategy to avoid name collisions is to create your own namespaces for your JavaScript
libraries. One pattern to consider using to create unique namespace names is the name of
the domain in reverse, such as
com.microsoft
. Because domain names are unique, this pattern
Search WWH ::
Custom Search