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

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. 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. 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 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 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 shows a rough outline. Listing Lightbox pseudo code var lightbox open function target return false close function . destroy function . create function Create or return container function anchorLightbox anchor options var lb lightbox lb options return lb Note that the code will not run as provided it s simply a conceptual example. The details of and will be explained in Chapter 7 Objects and Prototypal Inheritance and the

TỪ KHÓA LIÊN QUAN