Anandaraj
Anandaraj

Reputation: 161

Use of $.extend function in jQuery with multiple objecs

I am new to jQuery and I want to know about $.extend() function in jQuery.

Can anyone please explain the difference between following statements?

$.extend(true,ob1,ob2);

$.extend(true,{},ob1,ob2);

$.extend(true,ob1,{},ob2);

$.extend(true,ob1,ob2,{});

Thanks,

Anand

Upvotes: 0

Views: 105

Answers (2)

maqjav
maqjav

Reputation: 2434

Lets start with the definition of the extendfunction:

When two or more object arguments are supplied to$.extend(), properties from all of the objects are added to the target object. Arguments that are null or undefined are ignored.

Now lets see your example codes:

1. $.extend(true,ob1,ob2);

The target is ob1, this one is going to add the ob2 arguments to its parameters.

2. $.extend(true,{},ob1,ob2);

The target is a new object (defined with {}). This new object will have the arguments from both objects (ob1 and ob2).

3. $.extend(true,ob1,{},ob2);

The target is ob1, it will add the arguments from a new object (it doesn't make sence) and the object ob2. Does it work with the new object parameter?

4. $.extend(true,ob1,ob2,{});

The target is ob1, it will add the arguments from the object ob2 and from a new object (it doesn't make sence either). Does it work with the new object parameter?

Upvotes: 2

Henrik Andersson
Henrik Andersson

Reputation: 47172

It's best explained with a sample

var firstObject = {
    "hello": "jonkers",
};
var secondObject = {
    "stradivarius": "bonkers"
};
console.log(firstObject);
>> Object {hello: "jonkers"} 
$.extend(firstObject, secondObject);
console.log(firstObject);
>> Object {hello: "jonkers", stradivarius: "bonkers"}

But what does the true part mean? It's a boolean value that tells the $.extend function that a deep copy is supposed to take place.

A deep copy, you say!

There are two different types of "copying" when it comes to objects which applies to many languages and not just JavaScript and that's shallow and deep. Shallow copy is when you just take the references to that object (and all it contains) and make a duplicate leading to the values changed in copy_object is reflected in original_object. A deep copy is an actual brand spanking new object which you can manipulate three ways to sunday without it affecting the original_object.

The last example you're wanting to know about is the exact same call except it'll take several more objects to put in your first object. So the api call would be

$.extend(true, firstObject, secondObject, third, fourth, n-objects);

Reading more about this can be done

http://api.jquery.com/jQuery.extend/

http://blog.imaginea.com/deep-copy-in-javascript/

Upvotes: 3

Related Questions