tailieunhanh - Test Driven JavaScript Development- P5

Test Driven JavaScript Development- P5 | F . avaScript functions are powerful beasts. They are first class objects meaning they can be assigned to variables and as properties passed as arguments to functions have properties of their own and more. JavaScript also supports anonymous functions commonly used for inline callbacks to other functions and object methods. In this chapter we will cover the somewhat theoretical side of JavaScript functions providing us with the required background to easily dive into the more interesting uses of functions as we dig into into closures in Chapter 6 Applied Functions and Closures and methods and functions as a means to implement objects in Chapter 7 Objects and Prototypal Inheritance. Defining Functions Throughout the first part of this book we have already seen several ways to define functions. In this section we will go over the different ways JavaScript allows us to do so and investigate their pros and cons as well as some unexpected browser differences. Function Declaration The most straightforward way to define a function is by way of a function definition seen in Listing . Please purchase PDF Split-Merge on to remove this watermark. From the Library of 74 Functions Listing A function declaration function assert message expr if expr throw new Error message return true 0 This is the assert function from Chapter 1 Automated Testing. The function declaration starts with the keyword function followed by an identifier assert in the above example. The function may define one or more formal parameters . named arguments. Finally the function has a body enclosed in brackets. Functions may return a value. If no return statement is present or if it s present without an expression the function returns undefined. Being first class objects functions can also have properties assigned to them evident by the count property in the above example. Function Expression In addition to function declarations