tailieunhanh - Phát triển Javascript - part 14

Tham khảo tài liệu 'phát triển javascript - part 14', công nghệ thông tin, kỹ thuật lập trình phục vụ nhu cầu học tập, nghiên cứu và làm việc hiệu quả | Immediately Called Anonymous Functions 103 Listing Fixing scoping issues with nested closures function var anchors a var controller lightboxController var regexp A s lightbox s for var i 0 l i l i if anchors i .className function anchor function 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 . 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. 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 shows how we could possibly implement the lightbox object inside our own tddjs namespace. Listing Using objects as namespaces var tddjs lightbox . Download from 104 Applied Functions and Closures anchorLightbox function anchor options . In larger libraries we might want better organization than simply defining everything inside the same object. For example the lightbox might live in tddjs. ui whereas ajax functionality could live in . Many libraries provide some kind of namespace function to help with this kind of organizing. Organizing all code inside a single

TỪ KHÓA LIÊN QUAN