TAILIEUCHUNG - Test Driven JavaScript Development- P14

Test Driven JavaScript Development- P14: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. | Creating an XMLHttpRequest Object 253 will do as again ships with IE6 includes the alias for backwards compatibility. Implementing With knowledge of the different objects available we can take a shot at implementing as seen in Listing . Listing Creating an XMLHttpRequest object ajax .create function var options function return new ActiveXObject function return new XMLHttpRequest for var i 0 l i l i try return options i catch e return null Running the tests confirms that our implementation is sufficient. First test green Before we hasten on to the next test we should look for possible duplication and other areas that could be improved through refactoring. Although there is no obvious duplication in code there is already duplication in execution the try catch to find a suitable object is executed every time an object is created. This is wasteful and we can improve the method by figuring out which object is available before defining it. This has two benefits The call time overhead is eliminated and feature detection becomes built-in. If there is no matching object to create then there will be no which means that client code can simply test for its existence to determine if XMLHttpRequest is supported by the browser. Listing improves the method. Please purchase PDF Split-Merge on to remove this watermark. From the Library of 254 Abstracting Browser Differences Ajax Listing Checking for support upfront function var xhr var ajax ajax var options . Same as before for var i 0 l i l i try xhr options i options i break catch e With this implementation in place the try catch will only run at load time. If successfully created will call the correct function directly. The test still runs green so we can focus on the