NicholasAbrams
NicholasAbrams

Reputation: 69

What is the difference between these two JavaScript/JQuery techniques?

What is the difference between these two approaches? I am trying to understand Jquery and JavaScript better. Thanks in advance SO!

        /**
        * What is the difference between these two techniques?
        */

        /* Using JQuery Extend */

        var names = {name1 : 'Nicholas', name2: 'Bobby'}
        var ages = {age1 : '27', age2: '32'}
        var profile = $.extend(names, ages);
        console.log(profile.name1, profile.age1)

        /* By filling a blank object with the combined dataset */

        var names = { name1 : 'Nicholas', name2 : 'Bobby'}
        var ages = { age1 : '27', age2 : '32'}
        var profile = {};
        profile.names = names;
        profile.ages = ages;
        console.log(profile.names.name1, profile.ages.age1)

Upvotes: 0

Views: 85

Answers (3)

Thomas Junk
Thomas Junk

Reputation: 5676

Take a look at the Source of jQuery.fn.extend() in GitHub: It parses through the given object and makes a deep copy of the whole object. So, when the object has subobjects, they are deep copied too. The usage is explained here as follows:

Description: Merge the contents of two or more objects together into the first object.

Whereas

    var names = { name1 : 'Nicholas', name2 : 'Bobby'}
    var ages = { age1 : '27', age2 : '32'}
    var profile = {};
    profile.names = names;
    profile.ages = ages;

does not copy at all. It puts those objects together in one super- or wrapping-object.

The very difference is, that after extending, both objects are independend and with the second way not. See this Fiddle. The new object contains only references to the old objects instead of a deep copy.

Upvotes: 1

Barmar
Barmar

Reputation: 781058

$.extend merges two objects. The result of the first code is a single object containing all the properties of the two objects:

{name1 : 'Nicholas', age1: '27', name2: 'Bobby', age2: '32'}

It also modifies its first argument as a side effect. So this result will be in both profile and names. To prevent the first argument from being modified, use $.extend({}, names, ages).

To access one of the values from this, you would use profile.name1 or profile.age2.

Your second code creates a new object that contains the first two objects as different properties within it:

{ names: {name1 : 'Nicholas', name2: 'Bobby'},
  ages: { age1 : '27', age2 : '32'}
}

To access one of the values from this, you would use profile.names.name1 or profile.ages.age2.

Upvotes: 2

Zach
Zach

Reputation: 43

The jQuery extend method combines the names and ages objects. Your second example creates a new object with the preceding objects as keys.

Upvotes: 0

Related Questions