0

I have tried using other examples on Stackoverflow to extend jquery objects but i have been unsuccessful.

    var z = {

        vars: {
            x: $('#c')
        }

    };

    var y = {

        v: $(this).val(a),
        h: $(this).html(a)

    };

    $.extend(y,z);

    alert(y.vars.h.x);
5
  • 1
    did you mean y.vars.x? Commented Jun 16, 2013 at 23:46
  • Totally didn't read this before I answered. Commented Jun 16, 2013 at 23:53
  • This might help: api.jquery.com/jQuery.extend Commented Jun 17, 2013 at 0:15
  • y.vars.h.x - where is y.vars.h supposed to come from? Try alert(y.vars.x); Commented Jun 17, 2013 at 0:43
  • $.extend is supposed to essentially merge z with y, so that y includes vars and also v and h. So in your example y.v works, y.h works and y.vars works, as does y.vars.x. But y.vars.h.x makes no sense. Can you explain a bit more about what you're trying to accomplish with JQuery extend? Commented Jun 17, 2013 at 1:28

2 Answers 2

1

It looks like you have them extending correctly, you're just calling them wrong afterwards. I put the following together to help with debugging how it works.

var z = {
    vars: {
        x: "var_Z.X"
    }
};

var y = {
    v: "var_Y.V",
    h: "var_Y.H"
};

$.extend( y, z );

// Output
    ( y.vars.x ) // var_Z.X
    ( y.v ) // var_Y.V
    ( y.h ) // var_Y.H

    ( z.vars.x ) // var_Z.X
    ( z.v ) // undefined
    ( z.h ) // undefined

http://jsfiddle.net/daCrosby/6YvHw/

Sign up to request clarification or add additional context in comments.

Comments

0
jQuery.extend( target [, object1 ] [, objectN ] )

Keep in mind that the target object (first argument) will be modified, and will also be returned from $.extend().
If, however, you want to preserve both of the original objects, you can do so by passing an empty object as the target:

var object = $.extend({}, object1, object2);

Example:

var object1 = {
  apple: 0,
  banana: { weight: 52, price: 100 },
  cherry: 97
};
var object2 = {
  banana: { price: 200 },
  durian: 100
};

// Merge object2 into object1
$.extend( object1, object2 );

Output is:

{"apple":0,"banana":{"price":200},"cherry":97,"durian":100}

Explanation:

The merge performed by $.extend() is not recursive by default; if a property of the first object is itself an object or array, it will be completely overwritten by a property with the same key in the second or subsequent object.
The values are not merged. This can be seen in the example below by examining the value of banana. However, by passing true for the first function argument, objects will be recursively merged.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.