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.
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.