jQuery in Action

Manipulating JavaScript objects and collections
179
<p>
<label>target (after) =</label>
<span id="targetAfterDisplay"></span>
</p>
</fieldset>
</body>
</html>
In this simple example, we define three objects: a target and two source objects
b
. We'll use these objects to demonstrate what happens to the target when
$.extend
is used to merge the two sources into it.
After declaring the objects, we define a ready handler in which we'll operate
on them. Even though the objects are available immediately, we are going to dis-
play results on the page, so we need to wait until the
HTML
elements
f
have
been rendered to start playing around.
Within the ready handler, we display the state of the three objects in
<span>
ele-
ments defined to hold the results
c
. (If you're interested in how the
$.toSource()
function works, its definition can be found in the support.labs.js file. We'll address
adding such utility functions to our repertoire in the next chapter.)
We extend the target object with the two source objects
d
using the following:
$.extend(target,source1,source2);
This merges the properties from objects
source1
and
source2
into the
target
object. The
target
object is returned as the value of the function; but, because the
target
is modified in place, we don't need to create a variable to hold its refer-
ence. The fact that the
target
is returned is significant when using this function
as part of a statement chain.
Then, we display the values for the modified
target
e
. The results are as
shown in figure 6.5.
As we can see, all properties of the source objects have been merged into the
target
object. But note the following important nuances:
Both the
target
and
source1
contain a property named
c
. The value of
c
in
source1
replaces the value in the original target.
Both
source1
and
source2
contain a property named
e
. Note that the value
of
e
within
source2
takes precedence over the value within
source1
when
merged into
target
, demonstrating how objects later in the list of argu-
ments take precedence over those earlier in the list.


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

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