Currently, I am working on a JavaScript module that includes an object of default options. Here is a snippet of the code:
var myModule = function() {
// Define option defaults
var defaults = {
foo: 'bar',
fooObject: {
option1: [],
option2:true,
option3: false,
}
}
// Update options by merging defaults with the provided arguments
if (arguments[0] && typeof arguments[0] === "object") {
this.options = mergeDefaults(defaults, arguments[0]);
}
}
When calling my module like this:
var moduleInstance = new myModule({
foo: 'some value',
fooObject: {
option1: [1, 2, 3]
}
});
moduleInstance.options.foo; //will return an array [1, 2, 3]
However,
moduleInstance.options.fooObject; //will only contain option1
I understand why that happens since option2 and option3 are not defined initially. I am struggling to find a solution for this without relying on jQuery or other frameworks.
Edit: Potential Solution
I managed to address this issue in the following way: http://jsfiddle.net/optionsit/sgmme5dy/
In the loop where I check for hasOwnProperty...
I added this if statement:
if(typeof properties[property] === 'object' && typeof properties[property].nodeType === 'undefined' )
This allows me to differentiate between objects and DOM elements (as some top-level values are DOM elements) and iterate through their children to replace them if they are set in the arguments.
While it may not be the most elegant solution, it serves my needs. Feel free to suggest a better approach. I appreciate your input.
Thank you for your assistance