Đang chuẩn bị liên kết để tải về tài liệu:
Phát triển Javascript - part 13

Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ

Tham khảo tài liệu 'phát triển javascript - part 13', 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ả | Applied Functions and Closures In the previous chapter we discussed the theoretical aspects of JavaScript functions familiarizing ourselves with execution contexts and the scope chain. JavaScript supports nested functions which allows for closures that can keep private state and can be used for anything from ad hoc scopes to implementing memoization function binding modules and stateful functions and objects. In this chapter we will work through several examples of how to make good use of JavaScript functions and closures. 6.1 Binding Functions When passing methods as callbacks the implicit this value is lost unless the object on which it should execute is passed along with it. This can be confusing unless the semantics of this are familiar. 6.1.1 Losing this A Lightbox Example To illustrate the problem at hand assume we have a lightbox object. A lightbox is simply an HTML element that is overlaid the page and appears to float above the rest of the page much like a popup only with a web 2.0 name. In this example the lightbox pulls content from a URL and displays it in a div element. For convenience an anchorLightbox function is provided which turns an anchor element into a Download from www.eBookTM.com 93 94 Applied Functions and Closures lightbox toggler when the anchor is clicked the page it links to is loaded into a div that is positioned above the current page. Listing 6.1 shows a rough outline. Listing 6.1 Lightbox pseudo code var lightbox open function ajax.loadFragment this.url target this.create return false close function . destroy function . create function Create or return container function anchorLightbox anchor options var lb Object.create lightbox lb.url anchor.href lb.title anchor.title anchor.href Object.extend lb options anchor.onclick lb.open return lb Note that the code will not run as provided it s simply a conceptual example. The details of Object.create and Object.extend will be explained in Chapter 7 Objects and Prototypal Inheritance and the