jQuery in Action

Summary
337
Another important feature of closures is that a function context is never
included as part of the closure. For example, the following code won't execute as
we might expect:
...
this.id = 'someID';
$('*').each(function(){
alert(this.id);
});
Remember that each function invocation has its own function context so that, in
the code above, the function context within the callback function passed to
each()
is an element from the jQuery wrapped set, not the property of the outer function
set to
'someID'
. Each invocation of the callback function displays an alert box
showing the
id
of each element in the wrapped set in turn.
When access to the object serving as the function context in the outer function
is needed, we can employ a common idiom to create a copy of the
this
reference
in a local variable that will be included in the closure. Consider the following
change to our example:
this.id = 'someID';
var outer = this;
$('*').each(function(){
alert(outer.id);
});
The local variable
outer
, which is assigned a reference to the outer function's
function context, becomes part of the closure and can be accessed in the callback
function. The changed code now displays an alert showing the string
'someID'
as
many times as there are elements in the wrapped set.
We'll find closures indispensable when creating elegant code using jQuery
commands that utilize asynchronous callbacks, which is particularly true in the
areas of Ajax requests and event handling.
A.3 Summary
JavaScript is a language that's widely used across the web, but it's often not deeply
used by many of the page authors writing it. In this chapter, we introduced some
of the deeper aspects of the language that we must understand to use jQuery
effectively on our pages.
We saw that a JavaScript
Object
primarily exists to be a container for other
objects. If you have an
OO
background, thinking of an
Object
instance as an
unordered collection of name/value pairs may be a far cry from what you think of


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

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