Search code examples
jqueryjquery-pluginsextendjavascript-objects

Using Objects Inside of jQuery Plugin Defaults


I have a codepen representing my question: http://codepen.io/anon/pen/ibwvl

In the codepen, I create some simple plugin init functions and log out the settings when the app begins to run.

My question is, when I console.log(app.settings) I see my default object, along with the new options object merged together, but I do not see the last key inside of me defaults object (foo3). Is this because the default object is overwritten by the options object when $.extend() runs? If so, is there any way to merge nested objects with $.extend()?

For clarity:

default object:

var defaults = {
      test: 'foo',
      obj: {
        key1: null,
        key2: null,
        key3: 'foo3'
      }
    }

options object:

$('#foo').fooTest({
  obj: { 
    key1: 'foo1',
    key2: 'foo2'
  }
});

result when logging app.settings:

test: 'foo',
          obj: {
            key1: null,
            key2: null
          }
        }

Where did key3 go?

Was it overwritten because of the options plugin defining the new obj as obj: {}?

If so, how can I use extend with nested objects and ensure they don't get overwritten?


Solution

  • Yes, you object is being overwritten. But fortunately, $.extend accept boolean as first parameter that allow deep extension.

    Just do :

    app.settings = $.extend(true, defaults, options); //this will override defaults
    app.settings = $.extend(true, {}, defaults, options); //this will not
    //app.settings will be the same with both way
    

    Deep extension