Đang chuẩn bị liên kết để tải về tài liệu:
Phát triển Javascript - part 14
Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
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ả | 6.2 Immediately Called Anonymous Functions 103 Listing 6.13 Fixing scoping issues with nested closures function var anchors document.getElementsByTagName a var controller Object.create lightboxController var regexp A s lightbox s for var i 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 . Download from www.eBookTM.com 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 tddjs.ajax. Many libraries provide some kind of namespace function to help with this kind of organizing. Organizing all code inside a single