HTML and CSS Reference
In-Depth Information
Note that in contrast to function declarations, function expressions—like any
expression—should be terminated by a semicolon. Although not strictly necessary,
automatic semicolon insertion can cause unexpected results, and best practices
dictate that we always insert our own semicolons.
This alternative implementation of the
assert
function differs somewhat from
the previous one. The anonymous function has no name, and so can only refer to
itself by way of
arguments.callee
or through the
assert
variable, accessible
through the scope chain. We will discuss both the
arguments
object and the scope
chain in more detail shortly.
As noted previously, the identifier is optional in function expressions. Whether
named function expressions are still anonymous functions is a matter of definition,
but the functions stay anonymous to the enclosing scope. Listing 5.3 shows an
example of a named function expression. We will discuss the implications and cross-
browser issues surrounding named function expressions in Section 5.3.6,
Function
Expressions Revisited
.
Listing 5.3
A named function expression
var assert = function assert(message, expr) {
if (!expr) {
throw new Error(message);
}
assert.count++;
return true;
};
assert.count = 0;
5.1.3 The
Function
Constructor
JavaScript functions are first class objects, which means they can have properties,
including methods, of their own. Like any other JavaScript object, functions have
a prototype chain; functions inherit from
Function.prototype
, which in turn
inherits from
Object.prototype
.
1
The
Function.prototype
object pro-
vides a few useful properties, such as the
call
and
apply
methods. In addition
to the properties defined by their prototypes, function objects have
length
and
prototype
properties.
1. The details of JavaScript's prototypal inheritance are covered in Chapter 7,
Objects and Prototypal
Inheritance.