TAILIEUCHUNG - Test Driven JavaScript Development- P6

Test Driven JavaScript Development- P6:This book is about programming JavaScript for the real world, using the techniques and workflow suggested by Test-Driven Development. It is about gaining confidence in your code through test coverage, and gaining the ability to fearlessly refactor and organically evolve your code base. It is about writing modular and testable code. It is about writing JavaScript that works in a wide variety of environments and that doesn’t get in your user’s way. | 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 Please purchase PDF Split-Merge on to remove this watermark. From the Library of 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 .