jQuery in Action
326
APPENDIX
JavaScript that you need to know but might not!
It probably won't get us into conceptual trouble to think of top-level scope as
window scope because any unqualified references at the top level are assumed to be
window
properties. The scoping rules get more complex when we delve deeper
into the bodies of functions--much more complex, in fact--but we'll be address-
ing that soon enough.
ing that soon enough.
That pretty much covers things for our overview of the JavaScript
Object
. The
important concepts to take away from this discussion are
A JavaScript object is an unordered collection of properties.
Properties consist of a name and a value.
Objects can be declared using object literals.
Top-level variables are properties of
window
.
Now, let's discuss what we meant when we referred to JavaScript functions as first-
class objects.
class objects.
A.2 Functions as first-class citizens
In many traditional
OO
languages, objects can contain data, and they can possess
methods. In these languages the data and the methods are usually distinct con-
cepts; JavaScript walks a different path.
cepts; JavaScript walks a different path.
Functions in JavaScript are considered objects like any of the other object
types that are defined in JavaScript, such as
Strings
,
Numbers
, or
Dates
. Like
other objects, functions are defined by a JavaScript constructor--in this case
Function
--and can be
Assigned to variables
Assigned as a property of an object
Passed as a parameter
Returned as a function result
Created using literals
Because functions are treated in the same way as other objects in the language, we
say that functions are first-class objects.
say that functions are first-class objects.
But you might be thinking to yourself that functions are fundamentally differ-
ent from other object types like
String
or
Number
because they possess not only a
value (in the case of a
Function
instance, its body) but also a name.
Well, not so fast!