1

When I try to extend an object, passing in a full object, it seems to overwrite the desired target object. However, I can extend each subobject individually, and then pass those in and it works.

$(function() {
    window.test = {};
    $.extend(window.test, {
        init: function(opts1, opts2) {
            //method 1, completely overwrites            
            this.options = $.extend({}, this.settings, {opts1: opts1, opts2: opts2});

            //method 2, works
            this.a = $.extend({}, this.settings.opts1, opts1);
            this.b = $.extend({}, this.settings.opts2, opts2);
            this.options2 = $.extend({}, this.settings, {opts1: this.a, opts2: this.b});

            console.log(this.options, this.options2);
        },
        settings: {
            opts1: {
                a: 'hello',
                b: 'hi',
                e: 'this still here?'
            },
            opts2: {
                c: 'yo',
                d: 'wassup'
            }
        }
    });
    test.init({ a: 'hello2', b: 'hello3' });
});

My question is if there is a way to utilize the first method (a 1 line, simple method) to achieve the results of the second method (individual subobjects).

Also, here's a JSFiddle.

1
  • @crush yup... mark it as an answer. Thanks! Commented Jul 23, 2015 at 17:27

1 Answer 1

2

You can do a deep-copy extends by passing true as the first parameter to $.extend. I believe that is what you are asking here.

this.options = $.extend(true, this.settings, {opts1: opts1, opts2: opts2});

See the second definition in the documentation.

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

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.