HTML and CSS Reference
In-Depth Information
Listing 6.13 Fixing scoping issues with nested closures
(function () {
var anchors = document.getElementsByTagName("a");
var controller = Object.create(lightboxController);
var regexp = /(^ | \s)lightbox(\s | $ )/;
for(vari=0,l=anchors.length; i < l; i++) {
if (regexp.test(anchors[i].className)) {
(function (anchor) {
anchor.onclick = function () {
controller.open(anchor);
return false;
};
}(anchors[i]));
}
}
}());
anchor is now a formal parameter to the inner closure, whose variable object
cannot be accessed or tampered with by the containing scope. Thus, the event
handlers will work as expected.
Examples aside, closures in loops are generally a performance issue waiting
to happen. Most problems can be better solved by avoiding the nested closure,
for instance, by using dedicated functions to create the closure like we did in
Listing 6.11. When assigning event handlers, there is even another problem with
nesting functions like this, because the circular reference between the DOM element
and its event handler may cause memory leaks.
6.2.2 Namespaces
A good strategy to stay out of the global scope is to use some kind of namespacing.
JavaScript does not have native namespaces, but because it offers such useful objects
and functions it does not need them either. To use objects as namespaces, simply
define a single object in the global scope and implement additional functions and
objects as properties of it. Listing 6.14 shows how we could possibly implement the
lightbox object inside our own tddjs namespace.
Listing 6.14 Using objects as namespaces
var tddjs = {
lightbox: { /* ... */ },
 
Search WWH ::




Custom Search