jQuery in Action

Functions as first-class citizens
331
Silverado 1100 because the function picks up the properties of the object through
which it was invoked via
this
.
The same is true of top-level functions. Remember that top-level functions are
properties of
window
, so their function contexts, when called as top-level func-
tions, are the window objects.
Although that may be the usual and implicit behavior, JavaScript gives us the
means to explicitly control what's used as the function context. We can set the func-
tion context to whatever we want by invoking a function via the
Function
methods
call()
or
apply()
.
Yes, as first-class objects, even functions have methods as defined by the
Func-
tion
constructor.
The
call()
method invokes the function specifying, as its first parameter, the
object to serve as the function context, while the remainder of the parameters
become the parameters of the called function--the second parameter to
call()
becomes the first argument of the called function and so on. The
apply()
method
works in a similar fashion except that its second parameter is expected to be an
array of objects that become the arguments to the called function.
Confused? It's time for a more comprehensive example. Consider the code of
listing A.1 (found in the downloadable code as appendixA/function.context.html).
Figure A.3 This model clearly shows that the function isn't part of the Object but is only referenced
from the Object property named
whatAmI
.


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

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