JQuery: utility functions X – extending objects

This is the last post of the day on JQuery and we’re going to talk about extending objects with the extend utility function. The idea is simple: how can you add properties from an object to another and get a new object? For instance, suppose you’ve got these two anonymous objects:

var student = { name: "Luis", age: 20 };
var address = { street: "some street", civilParish: "somewhere"};

And now you’d like to add the address’ properties to the student object. You can do that by using the extend function:

var extendedStudent = $.extend(student, address);

If you’re using a debugger, you’ll notice that student has been “expanded” with the two properties defined on address:

extend

Notice that this method expects more parameters that the ones that we used in the previous snippet. If you pass several objects, you’ll end up adding the properties of all those objects to the first object. If some of the copied objects have properties with the same name, then the values of the last objects will override the initially copied values of the previous ones.

There’s also a first optional boolean parameter which you can use to indicate if you’re doing a deep or a shallow copy of the properties of the objects. This parameter is optional and you’ll end up with a shallow copy when you don’t specify a value.

And that it’s for today. I guess we’ve covered most of the current utility functions and now we’re ready to look at animations. Keep tuned for more on JQuery.

Advertisements

~ by Luis Abreu on August 10, 2009.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: