jQuery in Action

Functions as first-class citizens
327
A.2.1 What's in a name?
A large percentage of JavaScript programmers operate under a false assumption
that functions are named entities. Not so. If you're one of these programmers,
you've been fooled by a Jedi mind trick. As with other instances of objects--be they
Strings
,
Dates
, or
Numbers
--functions are referenced only when they are assigned to
variables, properties, or parameters.
Let's consider objects of type
Number
. We frequently express instances of
Number
by their literal notation such as
213
. The statement
213;
is perfectly valid, but it is also perfectly useless. The
Number
instance isn't all that
useful unless it has been assigned to a property or a variable, or bound to a param-
eter name. Otherwise, we have no way to reference the disembodied instance.
The same applies to instances of
Function
objects.
"But, but, but..." you might be saying, "what about the following code?"
function doSomethingWonderful() {
alert('does something wonderful');
}
"Doesn't that create a function named
doSomethingWonderful
?"
No, it doesn't. Although that notation may seem familiar and is ubiquitously
used to create top-level functions, it's the same syntactic sugar used by
var
to create
window
properties. The
function
keyword automatically creates a
Function
instance and assigns it to a
window
property created using the function "name"
(what we referred to earlier as a Jedi mind trick) as in the following:
doSomethingWonderful = function() {
alert('does something wonderful');
}
If that looks weird to you, consider another statement using the exact same for-
mat, except this time using a
Number
literal:
aWonderfulNumber = 213;
There's nothing strange about that, and the statement assigning a function to a
top-level variable (a.k.a.
window
property) is no different; a function literal is used
to create an instance of
Function
and then is assigned to the variable
doSome-
thingWonderful
in the same way that our
Number
literal
213
was used to assign a
Number
instance to the variable
aWonderfulNumber
.
If you've never seen the syntax for a function literal, it might seem odd. It's
composed of the keyword
function
, followed by its parameter list enclosed in
parentheses, then followed by the function body.


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.