HTML and CSS Reference
In-Depth Information
6.2 Immediately Called Anonymous Functions
A common practice in JavaScript is to create anonymous functions that are imme-
diately called. Listing 6.10 shows a typical incarnation.
Listing 6.10 An immediately called anonymous function
(function () {
/* ... */
}());
The parentheses wrapping the entire expression serves two purposes. Leaving
them out causes the function expression to be seen as a function declaration, which
would constitute a syntax error without an identifier. Furthermore, expressions (as
opposed to declarations) cannot start with the word “function” as it might make
them ambiguous with function declarations, so giving the function a name and
calling it would not work either. Thus, the parentheses are necessary to avoid syntax
errors. Additionally, when assigning the return value of such a function to a variable,
the leading parentheses indicates that the function expression is not what's returned
from the expression.
6.2.1 Ad Hoc Scopes
JavaScript only has global scope and function scope, which may sometimes cause
weird problems. The first problem we need to avoid is leaking objects into the
global scope, because doing so increases our chances of naming collisions with
other scripts, such as third party libraries, widgets, and web analytics scripts.
6.2.1.1 Avoiding the Global Scope
We can avoid littering the global scope with temporary variables (e.g., loop variables
and other intermittent variables) by simply wrapping our code in a self-executing
closure. Listing 6.11 shows an example of using the aforementioned lightbox object;
every anchor element in the document with the class name lightbox is picked up
and passed to the anchorLightbox function.
Listing 6.11 Creating lightboxes
(function () {
var anchors = document.getElementsByTagName("a");
var regexp = /(^ | \s)lightbox(\s | $ )/;
for(vari=0,l=anchors.length; i < l; i++) {
 
 
Search WWH ::




Custom Search