HTML and CSS Reference
In-Depth Information
Listing 5.1 A function declaration
function assert(message, expr) {
if (!expr) {
throw new Error(message);
}
assert.count++;
return true;
}
assert.count = 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 , i.e.,
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.
5.1.2 Function Expression
In addition to function declarations, JavaScript supports function expressions. A
function expression results in an anonymous function that may be immediately exe-
cuted, passed to another function, returned from a function, or assigned to a variable
or an object property. In function expressions the identifier is optional. Listing 5.2
shows the assert function from before implemented as a function expression.
Listing 5.2 An anonymous function expression
var assert = function (message, expr) {
if (!expr) {
throw new Error(message);
}
assert.count++;
return true;
};
assert.count = 0;
 
Search WWH ::




Custom Search